Skip to content

Commit 2988534

Browse files
committed
* Method to get JSON object value using Poco::Nullable
1 parent fd6433e commit 2988534

2 files changed

Lines changed: 21 additions & 0 deletions

File tree

JSON/include/Poco/JSON/Object.h

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
#include "Poco/SharedPtr.h"
4747
#include "Poco/Dynamic/Var.h"
4848
#include "Poco/Dynamic/Struct.h"
49+
#include "Poco/Nullable.h"
4950
#include <map>
5051
#include <vector>
5152
#include <deque>
@@ -144,6 +145,22 @@ class JSON_API Object
144145
return value.convert<T>();
145146
}
146147

148+
template<typename T>
149+
Poco::Nullable<T> getNullableValue(const std::string& key) const
150+
/// Retrieves the property with the given name and will
151+
/// try to convert the value to the given template type.
152+
/// Returns null if isNull.
153+
/// The convert<T> method of Dynamic is called
154+
/// which can also throw exceptions for invalid values.
155+
/// Note: This will not work for an array or an object.
156+
{
157+
if (isNull(key))
158+
return Poco::Nullable<T>();
159+
160+
Dynamic::Var value = get(key);
161+
return value.convert<T>();
162+
}
163+
147164
void getNames(std::vector<std::string>& names) const;
148165
/// Returns all property names
149166

JSON/testsuite/src/JSONTest.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
#include "Poco/UTF8Encoding.h"
5252
#include "Poco/Latin1Encoding.h"
5353
#include "Poco/TextConverter.h"
54+
#include "Poco/Nullable.h"
5455

5556
#include "Poco/Dynamic/Struct.h"
5657

@@ -105,6 +106,9 @@ void JSONTest::testNullProperty()
105106
Var test = object->get("test");
106107
assert(test.isEmpty());
107108

109+
Poco::Nullable<int> test2 = object->getNullableValue<int>("test");
110+
assert(test2.isNull());
111+
108112
DynamicStruct ds = *object;
109113
assert (ds["test"].isEmpty());
110114

0 commit comments

Comments
 (0)