|
◆ get() [5/6]
template<typename ValueTypeCV , typename ValueType = detail::uncvref_t<ValueTypeCV>, detail::enable_if_t< not detail::is_basic_json< ValueType >::value and detail::has_from_json< basic_json_t, ValueType >::value and not detail::has_non_default_from_json< basic_json_t, ValueType >::value, int > = 0>
ValueType nlohmann::basic_json::get |
( |
| ) |
const |
|
inlinenoexcept |
Explicit type conversion between the JSON value and a compatible value which is CopyConstructible and DefaultConstructible. The value is converted by calling the json_serializer<ValueType> from_json() method.
The function is equivalent to executing ValueType ret;
JSONSerializer<ValueType>::from_json(*this, ret);
return ret;
This overloads is chosen if:
- Template Parameters
-
ValueTypeCV | the provided value type |
ValueType | the returned value type |
- Returns
- copy of the JSON value, converted to ValueType
- 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}},
25 auto v1 = json_types[ "boolean"].get< bool>();
26 auto v2 = json_types[ "number"][ "integer"].get< int>();
27 auto v3 = json_types[ "number"][ "integer"].get< short>();
28 auto v4 = json_types[ "number"][ "floating-point"].get< float>();
29 auto v5 = json_types[ "number"][ "floating-point"].get< int>();
30 auto v6 = json_types[ "string"].get<std::string>();
31 auto v7 = json_types[ "array"].get<std::vector<short>>();
32 auto v8 = json_types.get<std::unordered_map<std::string, json>>();
35 std::cout << v1 << '\n';
36 std::cout << v2 << ' ' << v3 << '\n';
37 std::cout << v4 << ' ' << v5 << '\n';
38 std::cout << v6 << '\n';
42 std::cout << i << ' ';
48 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__ValueType_const.cpp -o get__ValueType_const
- Since
- version 2.1.0
Definition at line 17174 of file json.hpp.
|