【问题标题】:Why nlohmann/json serialize "null" instead of "0" on double?为什么 nlohmann/json 在 double 上序列化“null”而不是“0”?
【发布时间】:2019-03-13 21:13:57
【问题描述】:

假设我在 C++ 中部分初始化了一个原生双精度数组,并使用 nlohmann/json 对其进行序列化:

const int numPoints = 10;
double mLengths[numPoints];
for (int i = 0; i < 5; i++) {
    mLengths[i] = i + 0.1 * i; 
}

nlohmann::json jsonData;
jsonData["lengths"] = mLengths;
std::string serialized_string = jsonData.dump();

它将正确序列化如下内容:

{  
   "lengths":[  
      0.0,
      1.1,
      2.2,
      3.3,
      4.4,
      -9.255963134931783e+61,
      -9.255963134931783e+61,
      -9.255963134931783e+61,
      -9.255963134931783e+61,
      -9.255963134931783e+61
   ]
}

但有时,它不是从内存中获取“随机双精度”,而是将值 null 存储在 json 中,因此会产生如下结果:

{  
   "lengths":[  
      0.0,
      1.1,
      2.2,
      3.3,
      4.4,
      -9.255963134931783e+61,
      -9.255963134931783e+61,
      null,
      -9.255963134931783e+61,
      -9.255963134931783e+61
   ]
}

当我反序列化它时,它抛出了一个异常type must be number, but is null

为什么它序列化null 而不是0?它是否会从记忆中获取“空”的东西? C++中不是0吗?

【问题讨论】:

    标签: c++ json serialization null nlohmann-json


    【解决方案1】:

    序列化步骤的行为,因此自相矛盾的是整个程序,未定义

    在 C++ 中,您必须从不尝试读取未初始化的内存,除非您强制转换为 unsigned char 类型。

    变化输出的“有时”性质是这种未定义行为的表现。

    【讨论】:

    • 你能告诉我一个例子如何将双精度存储为“null”而不是“0”吗?
    • @markzzz:如果没有看到所有的序列化代码,那将很难被删除。
    • @markzzz:不是真的,dump 中的所有代码都需要检查。
    • 它是一个免费的图书馆,它的开放:github.com/nlohmann/json/blob/develop/single_include/nlohmann/…
    猜你喜欢
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多