3

我正在使用 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,我所拥有的不起作用(对于两个查询都存在错误),但它对以下 JSON 起作用。我确定这与对“路径”到“a”键的“路径”使用哪个键的误解有关。

{      
   "a": "1",
   "b": "2",
   "c": "3"
}
4

1 回答 1

2

好的,我想通了,就像我说的那样,我误解了 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; 
}
于 2015-04-18T20:59:14.723 回答