• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# <small>nlohmann::adl_serializer::</small>from_json
2
3```cpp
4// (1)
5template<typename BasicJsonType, typename TargetType = ValueType>
6static auto from_json(BasicJsonType && j, TargetType& val) noexcept(
7    noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
8-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
9
10// (2)
11template<typename BasicJsonType, typename TargetType = ValueType>
12static auto from_json(BasicJsonType && j) noexcept(
13noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {})))
14-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}))
15```
16
17This function is usually called by the [`get()`](../basic_json/get.md) function of the [basic_json](../basic_json)
18class (either explicitly or via the conversion operators).
19
201. This function is chosen for default-constructible value types.
212. This function is chosen for value types which are not default-constructible.
22
23## Parameters
24
25`j` (in)
26:   JSON value to read from
27
28`val` (out)
29:   value to write to
30
31## Return value
32
33Copy of the JSON value, converted to `ValueType`
34
35## Examples
36
37??? example "Example: (1) Default-constructible type"
38
39    The example below shows how a `from_json` function can be implemented for a user-defined type. This function is
40    called by the `adl_serializer` when `get<ns::person>()` is called.
41
42    ```cpp
43    --8<-- "examples/from_json__default_constructible.cpp"
44    ```
45
46    Output:
47
48    ```json
49    --8<-- "examples/from_json__default_constructible.output"
50    ```
51
52??? example "Example: (2) Non-default-constructible type"
53
54    The example below shows how a `from_json` is implemented as part of a specialization of the `adl_serializer` to
55    realize the conversion of a non-default-constructible type.
56
57    ```cpp
58    --8<-- "examples/from_json__non_default_constructible.cpp"
59    ```
60
61    Output:
62
63    ```json
64    --8<-- "examples/from_json__non_default_constructible.output"
65    ```
66
67## See also
68
69- [to_json](to_json.md)
70
71## Version history
72
73- Added in version 2.1.0.
74