简体   繁体   English

为什么jsoncpp append函数会导致assert错误

[英]Why jsoncpp append function will cause an assert error

I am a newer to Jsoncpp and I used it in my c++ projects。Sometimes I found a wired error like this:我是 Jsoncpp 的新手,我在我的 c++ 项目中使用了它。 有时我发现一个像这样的连线错误:

Json::Value val;
val["1"] = 1;
val["2"] = 2;

Json::Value arr;
arr["name"] = "wjx";
arr["age"] = 23;
arr["id"] = 17777;

val.append(arr);

this will cause a error named Json::throwLogicError,But the similar code below run rightly这会导致一个名为 Json::throwLogicError 的错误,但下面类似的代码运行正确

Json::Value val;
val["first"] = 1;
val["second"] = 2;

val["fourth"] = "wjx";

Json::Value root;
root.append(val);

I don't konw the reason,And I find no talk on the Internet so I ask for help.Who can explain this sitution.不知道是什么原因,网上也找不到什么说法,求助。谁能解释一下。

append only makes sense for arrayValue , that is list-type JSON values. append仅对arrayValue ,即列表类型的 JSON 值。

When jsoncpp creates a value, by default, it starts as a nullValue .当 jsoncpp 创建一个值时,默认情况下,它以nullValue开始。 If you then perform array-style operations on it like append , it'll turn it into an arrayValue and carry on.如果然后对它执行数组样式的操作,例如append ,它将把它变成一个arrayValue并继续。 This is what happens when you write这就是你写的时候发生的事情

Json::Value root; // Root starts as a nullValue
root.append(val); // Root becomes an arrayValue
                  // and from now on array-type behaviors are okay

But that doesn't work in your first code snippet.但这在您的第一个代码片段中不起作用。 Because similarly to append causing a conversion from nullValue to arrayValue , using operator[] with string keys to do assignment converts it into an objectValue , a collection of key-value pairs.因为类似于append导致从nullValuearrayValue的转换,使用带有字符串键的operator[]进行赋值会将其转换为objectValue ,即键值对的集合。 ( operator[] with integer keys would have turned it into an arrayValue , since in a JSON object keys must be strings.) (带有整数键的operator[]会将它变成一个arrayValue ,因为在 JSON 对象中,键必须是字符串。)

Json::Value val; // val starts as a nullValue
val["1"] = 1;    // val becomes an objectValue
                 // and from now on dict-style operations are okay
val["2"] = 2;

...

val.append(arr); // ERROR: val only accepts dict-style operations

To see why a dict-style Value can't accept append , ask yourself what key should be associated with the value you're append ing.要了解为什么 dict 样式的Value不能接受append ,请问问自己应该将哪个键与要append的值相关联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM