diff --git a/Message/Json.cpp b/Message/Json.cpp index ab0f70c4..480855dd 100644 --- a/Message/Json.cpp +++ b/Message/Json.cpp @@ -106,6 +106,16 @@ float Json::AsFloat() const return s.ToFloat(); } +double Json::AsDouble() const +{ + if(!_str && !_len) return 0; + + if(Type() != JsonType::Float) return 0; + + String s((cstring)_str, _len); + return s.ToDouble(); +} + // 跳过空格 cstring SkipSpace(cstring str) { diff --git a/Message/Json.h b/Message/Json.h index 2ed7a9dc..48cd2ad0 100644 --- a/Message/Json.h +++ b/Message/Json.h @@ -39,6 +39,7 @@ public: bool AsBoolean() const; int AsInt() const; float AsFloat() const; + double AsDouble() const; // 读取成员。找到指定成员,并用它的值构造一个新的对象 Json operator[](cstring key) const; diff --git a/Test/JsonTest.cpp b/Test/JsonTest.cpp index 42569696..d3a72583 100644 --- a/Test/JsonTest.cpp +++ b/Test/JsonTest.cpp @@ -10,7 +10,7 @@ static void TestRead() \"name\": \"Stone\", \ \"enable\": true, \ \"noval\": null, \ - \"score\": 3.1415, \ + \"score\": 3.14159, \ \"array\": [1, 0, 2], \ \"extend\": { \ \"kind\": \"cost\", \ @@ -37,11 +37,18 @@ static void TestRead() auto score = json["score"]; assert(score.Type() == JsonType::Float, "Type()"); - assert(score.AsFloat() == 3.1415, "AsFloat()"); + float v = score.AsFloat(); + String s(v); + s.Show(true); + double v2 = score.AsDouble(); + //double v2 = 3.1415; + String s2(v2); + s2.Show(true); + assert(score.AsDouble() == 3.14159, "AsFloat()"); auto array = json["array"]; assert(array.Type() == JsonType::array, "Type()"); - assert(score.Length() == 3, "Length()"); + //assert(score.Length() == 3, "Length()"); auto extend = json["extend"]; assert(extend.Type() == JsonType::object, "Type()");