From 6fffb96b660cac7a77a55b3bfa829d9b4aa8f724 Mon Sep 17 00:00:00 2001 From: PengZheng Date: Sat, 20 Jan 2024 15:20:04 +0800 Subject: [PATCH] Support nullptr when serialize text. --- libs/dfi/gtest/src/json_serializer_tests.cpp | 40 ++++++++++++++++++++ libs/dfi/src/json_serializer.c | 6 ++- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/libs/dfi/gtest/src/json_serializer_tests.cpp b/libs/dfi/gtest/src/json_serializer_tests.cpp index 3c88d40dc..20bdf7253 100644 --- a/libs/dfi/gtest/src/json_serializer_tests.cpp +++ b/libs/dfi/gtest/src/json_serializer_tests.cpp @@ -946,3 +946,43 @@ TEST_F(JsonSerializerTests, SerializationDeserilizationTest) { dynType_free(type, inst); dynType_destroy(type); } + +TEST_F(JsonSerializerTests, SerializationDeserilizationNullStringTest) { + dyn_type *type; + void *inst; + int rc; + rc = dynType_parseWithStr("t", nullptr, nullptr, &type); + ASSERT_EQ(0, rc); + json_auto_t* root = json_null(); + rc = jsonSerializer_deserializeJson(type, root, &inst); + ASSERT_EQ(0, rc); + EXPECT_EQ(nullptr, *(char**)inst); + + json_auto_t* result = nullptr; + rc = jsonSerializer_serializeJson(type, inst, &result); + ASSERT_EQ(0, rc); + EXPECT_TRUE(json_equal(root, result)); + dynType_free(type, inst); + dynType_destroy(type); + +} + +TEST_F(JsonSerializerTests, SerializationDeserilizationStringTest) { + dyn_type *type; + void *inst; + int rc; + rc = dynType_parseWithStr("t", nullptr, nullptr, &type); + ASSERT_EQ(0, rc); + json_auto_t* root = json_loads(R"("hello")", JSON_DECODE_ANY, NULL); + ASSERT_NE(nullptr, root); + rc = jsonSerializer_deserializeJson(type, root, &inst); + ASSERT_EQ(0, rc); + EXPECT_STREQ("hello", *(char**)inst); + + json_auto_t* result = nullptr; + rc = jsonSerializer_serializeJson(type, inst, &result); + ASSERT_EQ(0, rc); + EXPECT_TRUE(json_equal(root, result)); + dynType_free(type, inst); + dynType_destroy(type); +} diff --git a/libs/dfi/src/json_serializer.c b/libs/dfi/src/json_serializer.c index f6f964f9b..d98451fe1 100644 --- a/libs/dfi/src/json_serializer.c +++ b/libs/dfi/src/json_serializer.c @@ -320,9 +320,11 @@ static int jsonSerializer_writeAny(const dyn_type* type, const void* input, json case 'D' : val = json_real(*(const double*)input); break; - case 't' : - val = json_string(*(const char **) input); + case 't' : { + const char *strValue = *(const char **) input; + val = (strValue != NULL) ? json_string(strValue) : json_null(); break; + } case 'E': status = jsonSerializer_writeEnum(type, *(const int32_t*)input, &val); break;