|
◆ get_to() [2/2]
template<typename ValueType , detail::enable_if_t< not detail::is_basic_json< ValueType >::value and detail::has_from_json< basic_json_t, ValueType >::value, int > = 0>
ValueType& nlohmann::basic_json::get_to |
( |
ValueType & |
v | ) |
const |
|
inlinenoexcept |
Explicit type conversion between the JSON value and a compatible value. The value is filled into the input parameter by calling the json_serializer<ValueType> from_json() method.
The function is equivalent to executing ValueType v;
JSONSerializer<ValueType>::from_json(*this, v);
This overloads is chosen if:
- Template Parameters
-
ValueType | the input parameter type. |
- Returns
- the input parameter, allowing chaining calls.
- Exceptions
-
- Example
- The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard
std::vector<short> , (3) A JSON object can be converted to C++ associative containers such as std::unordered_map<std::string, json> .
2 #include <unordered_map>
3 #include <nlohmann/json.hpp>
16 { "floating-point", 17.23}
19 { "string", "Hello, world!"},
20 { "array", {1, 2, 3, 4, 5}},
30 std::vector<short> v7;
31 std::unordered_map<std::string, json> v8;
35 json_types[ "boolean"].get_to(v1);
36 json_types[ "number"][ "integer"].get_to(v2);
37 json_types[ "number"][ "integer"].get_to(v3);
38 json_types[ "number"][ "floating-point"].get_to(v4);
39 json_types[ "number"][ "floating-point"].get_to(v5);
40 json_types[ "string"].get_to(v6);
41 json_types[ "array"].get_to(v7);
42 json_types.get_to(v8);
45 std::cout << v1 << '\n';
46 std::cout << v2 << ' ' << v3 << '\n';
47 std::cout << v4 << ' ' << v5 << '\n';
48 std::cout << v6 << '\n';
52 std::cout << i << ' ';
58 std::cout << i.first << ": " << i.second << '\n';
Output (play with this example online): 1
42 42
17.23 17
Hello, world!
1 2 3 4 5
string: "Hello, world!"
number: {"floating-point":17.23,"integer":42}
null: null
boolean: true
array: [1,2,3,4,5]
The example code above can be translated withg++ -std=c++11 -Isingle_include doc/examples/get_to.cpp -o get_to
- Since
- version 3.3.0
Definition at line 17271 of file json.hpp.
|