为什么nlohmann / json在序列号上将“ null”而不是“ 0”序列化?

时间:2018-10-09 07:06:05

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

假设我在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?

1 个答案:

答案 0 :(得分:3)

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

在C ++中,您必须从不尝试读取未初始化的内存,除非您将其强制转换为 .opacity-animation{ -webkit-animation-name: flickerAnimation; -webkit-animation-duration: 2s; -webkit-animation-iteration-count: infinite; -webkit-animation-timing-function: ease-in-out; -webkit-animation-delay: 0.5s; } @keyframes flickerAnimation { 0% { opacity:1; } 50% { opacity:0; } 100% { opacity:1; } } @-o-keyframes flickerAnimation{ 0% { opacity:1; } 50% { opacity:0; } 100% { opacity:1; } } @-moz-keyframes flickerAnimation{ 0% { opacity:1; } 50% { opacity:0; } 100% { opacity:1; } } @-webkit-keyframes flickerAnimation{ 0% { opacity:1; } 50% { opacity:0; } 100% { opacity:1; } } 类型。

变化的输出的“有时”性质是这种不确定行为的体现。

相关问题