From f251563af1674195e595dc9a950d30081213e347 Mon Sep 17 00:00:00 2001 From: Benoit Blanchon Date: Tue, 30 Sep 2014 17:32:45 +0200 Subject: [PATCH] Serialize floats in objects --- srcs/JsonObject.cpp | 3 +++ srcs/JsonValue.cpp | 7 ++++++- srcs/JsonValue.h | 5 +++-- tests/JsonObjectSerializationTests.cpp | 6 +++--- 4 files changed, 15 insertions(+), 6 deletions(-) diff --git a/srcs/JsonObject.cpp b/srcs/JsonObject.cpp index 23b74073..c1f359cd 100644 --- a/srcs/JsonObject.cpp +++ b/srcs/JsonObject.cpp @@ -124,6 +124,9 @@ size_t JsonObject::printTo(Print& p) const break; } + if (childValue->type >= JSON_DOUBLE_0_DECIMALS) + n += p.print(childValue->content.asDouble, childValue->type - JSON_DOUBLE_0_DECIMALS); + if (child->next) { n += p.write(','); diff --git a/srcs/JsonValue.cpp b/srcs/JsonValue.cpp index 528a6bb1..10bad2f8 100644 --- a/srcs/JsonValue.cpp +++ b/srcs/JsonValue.cpp @@ -19,10 +19,15 @@ void JsonValue::operator=(char const* value) } void JsonValue::operator=(double value) +{ + set(value, 2); +} + +void JsonValue::set(double value, int decimals) { if (!_node) return; - _node->type = JSON_DOUBLE_2_DECIMALS; + _node->type = (JsonNodeType) (JSON_DOUBLE_0_DECIMALS + decimals); _node->content.asDouble = value; } diff --git a/srcs/JsonValue.h b/srcs/JsonValue.h index 86ff287d..f668e3f4 100644 --- a/srcs/JsonValue.h +++ b/srcs/JsonValue.h @@ -29,10 +29,11 @@ public: operator int() const; operator JsonObject() const; + void set(double value, int decimals); + private: JsonNode* _node; void setAsProxyTo(JsonNode*); JsonNode* getActualNode() const; -}; - +}; \ No newline at end of file diff --git a/tests/JsonObjectSerializationTests.cpp b/tests/JsonObjectSerializationTests.cpp index 3e526905..9b293aaf 100644 --- a/tests/JsonObjectSerializationTests.cpp +++ b/tests/JsonObjectSerializationTests.cpp @@ -95,10 +95,10 @@ TEST_F(JsonObjectSerializationTests, OneInteger) object["key"] = 1; outputMustBe("{\"key\":1}"); } -/* + TEST_F(JsonObjectSerializationTests, OneDoubleFourDigits) { - object["key"].set<4>(3.14159265358979323846); + object["key"].set(3.14159265358979323846, 4); outputMustBe("{\"key\":3.1416}"); } @@ -107,7 +107,7 @@ TEST_F(JsonObjectSerializationTests, OneDoubleDefaultDigits) object["key"] = 3.14159265358979323846; outputMustBe("{\"key\":3.14}"); } - +/* TEST_F(JsonObjectSerializationTests, OneNull) { object["key"] = (char*) 0;