我正在使用json-c解析以下JSON字符串:
{
"root": {
"a": "1",
"b": "2",
"c": "3"
}
}
而且,我有以下C代码。上面的JSON存储在变量b中。
json_object *new_obj, *obj1, *obj2;
int exists;
new_obj = json_tokener_parse(b);
exists=json_object_object_get_ex(new_obj,"a",&obj1);
if(exists==false) {
printf("key \"a\" not found in JSON");
return;
}
exists=json_object_object_get_ex(new_obj,"b",&obj2);
if(exists==false) {
printf("key \"b\" not found in JSON");
return;
}
使用json_object_get_ex从键“ a”获取值时使用的正确键名是什么?
我上面的JSON不起作用(两个查询都存在false),但对于以下JSON却起作用。我敢肯定,这与对密钥“ a”的“路径”使用哪个密钥的误解有关。
{
"a": "1",
"b": "2",
"c": "3"
}
好的,我弄清楚了,就像我说的那样,我误会了json-c如何解析原始JSON文本并将其表示为父节点和子节点。
以下代码正在运行。问题是我试图从原始的json_object获取子节点,这是不正确的。我首先必须获取根对象,然后再从根获取子对象。
json_object *new_obj, *root_obj, *obj1, *obj2;
int exists;
new_obj = json_tokener_parse(b);
exists=json_object_object_get_ex(new_obj,"root",&root_obj);
if(exists==false) {
printf("\"root\" not found in JSON");
return;
}
exists=json_object_object_get_ex(root_obj,"a",&obj1);
if(exists==false) {
printf("key \"a\" not found in JSON");
return;
}
exists=json_object_object_get_ex(root_obj,"b",&obj2);
if(exists==false) {
printf("key \"b\" not found in JSON");
return;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句