EXPECT_EQ(static_cast<int>(json["int"]), 1);
}
+TEST(JsonTests, double)
+{
+ Json json;
+ json["double"] = 1.1;
+
+ double value = json["double"];
+ EXPECT_EQ(value, 1.1);
+
+ json["double"] = -1.1;
+ value = json["double"];
+ EXPECT_EQ(value, -1.1);
+
+ EXPECT_EQ(static_cast<double>(json["double"]), -1.1);
+
+ EXPECT_NE(json["double"].serialize().find("-1.1"), std::string::npos);
+
+ json["double"].deserialize("1.1");
+ EXPECT_EQ(static_cast<double>(json["double"]), 1.1);
+}
+
TEST(JsonTests, int_type_mismatch)
{
Json json;
namespace json {
struct Bool;
+struct Double;
struct Int;
-struct String;
struct Null;
+struct String;
struct Array;
struct Object;
case 'n': this->convert<Null>(); break;
case 't': // fall through
case 'f' : this->convert<Bool>(); break;
- default : this->convert<Int>();
+ default : {
+ if (dumped.find(".") == std::string::npos)
+ this->convert<Int>();
+ else
+ this->convert<Double>();
+ }
}
this->leaf->deserialize(dumped);
{
if constexpr (std::is_same_v<Type, int>)
this->leaf = std::make_shared<Int>(data);
+ else if constexpr (std::is_same_v<Type, double>)
+ this->leaf = std::make_shared<Double>(data);
else if constexpr (std::is_same_v<typename std::decay<Type>::type, std::string> ||
std::is_same_v<typename std::decay<Type>::type, char*>)
this->leaf = std::make_shared<String>(data);
return (*this->leaf).operator int();
}
+ virtual operator double()
+ {
+ if (auto downcast = std::dynamic_pointer_cast<Double>(this->leaf); downcast == nullptr)
+ throw std::runtime_error("Mismatched type.");
+
+ return (*this->leaf).operator double();
+ }
+
virtual operator std::string()
{
if (auto downcast = std::dynamic_pointer_cast<String>(this->leaf); downcast == nullptr)
int data = 0;
};
+struct Double : public Value {
+ explicit Double() {}
+ explicit Double(double data) : data(data) {}
+
+ std::string serialize() const override
+ {
+ return std::to_string(data);
+ }
+
+ void deserialize(const std::string& dumped) override
+ {
+ this->data = std::stod(dumped);
+ }
+
+ operator double() override
+ {
+ return data;
+ }
+
+ double data = 0.0;
+};
+
struct String : public Value {
explicit String() {}
explicit String(const std::string& data) : data(data) {}