diff options
Diffstat (limited to 'library/cpp')
| -rw-r--r-- | library/cpp/json/writer/json_value.cpp | 7 | ||||
| -rw-r--r-- | library/cpp/json/writer/json_value.h | 1 | ||||
| -rw-r--r-- | library/cpp/json/writer/json_value_ut.cpp | 8 |
3 files changed, 16 insertions, 0 deletions
diff --git a/library/cpp/json/writer/json_value.cpp b/library/cpp/json/writer/json_value.cpp index 6a0546fe043..22f2b2c07a2 100644 --- a/library/cpp/json/writer/json_value.cpp +++ b/library/cpp/json/writer/json_value.cpp @@ -455,6 +455,13 @@ namespace NJson { return Value.String; } + TString& TJsonValue::GetStringSafe() { + if (!IsString()) { + ythrow TJsonException() << "Not a string"; + } + return Value.String; + } + bool TJsonValue::GetBooleanSafe(const bool defaultValue) const { if (Type == JSON_UNDEFINED) { return defaultValue; diff --git a/library/cpp/json/writer/json_value.h b/library/cpp/json/writer/json_value.h index 6b20af7f4cb..fc07466ee24 100644 --- a/library/cpp/json/writer/json_value.h +++ b/library/cpp/json/writer/json_value.h @@ -125,6 +125,7 @@ namespace NJson { unsigned long long GetUIntegerSafe() const; double GetDoubleSafe() const; const TString& GetStringSafe() const Y_LIFETIME_BOUND; + TString& GetStringSafe() Y_LIFETIME_BOUND; const TMapType& GetMapSafe() const Y_LIFETIME_BOUND; TMapType& GetMapSafe() Y_LIFETIME_BOUND; const TArray& GetArraySafe() const Y_LIFETIME_BOUND; diff --git a/library/cpp/json/writer/json_value_ut.cpp b/library/cpp/json/writer/json_value_ut.cpp index 21b396a64de..e804e541ccf 100644 --- a/library/cpp/json/writer/json_value_ut.cpp +++ b/library/cpp/json/writer/json_value_ut.cpp @@ -682,4 +682,12 @@ Y_UNIT_TEST_SUITE(TJsonValueTest) { UNIT_ASSERT_VALUES_EQUAL(filled["4"].GetMapSafe().size(), 1); UNIT_ASSERT_VALUES_EQUAL(filled["4"]["5"], TJsonValue{5}); } + + Y_UNIT_TEST(GetStringSafeTest) { + TJsonValue json; + json["key"] = "value"; + TString& valueRef = json["key"].GetStringSafe(); + valueRef = "new_value"; + UNIT_ASSERT_VALUES_EQUAL(json["key"].GetString(), "new_value"); + } } // Y_UNIT_TEST_SUITE(TJsonValueTest) |
