使用cJSON读取JSON数组 [英] Using cJSON to read in a JSON array
问题描述
我正在尝试使用Dave Gamble编写的cJSON库来读取以下JSON数组:
I am attempting to use the cJSON library, written by Dave Gamble, to read in the following JSON array:
"items":
[
{
"name": "command",
"index": "X",
"optional": "0"
},
{
"name": "status",
"index": "X",
"optional": "0"
}
]
通过阅读他的文档,我找到了单独阅读的方法对象,但是没有关于数组的任何知识,我无法从给出的示例中推测出如何做到这一点.
From reading his documentation, I found ways to read in individual Objects, but nothing regarding Arrays, and I wasn't able to surmise how to do it from the examples given.
这就是我要尝试的:
cJSON* request_json = NULL;
cJSON* items = cJSON_CreateArray();
cJSON* name = NULL;
cJSON* index = NULL;
cJSON* optional = NULL;
request_json = cJSON_Parse(request_body);
items = cJSON_GetObjectItem(request_json, "items");
name = cJSON_GetObjectItem(items, "name");
index = cJSON_GetObjectItem(items, "index");
optional = cJSON_GetObjectItem(items, "optional");
我知道这是错误的,不仅仅是因为它不起作用,而且我不知道该怎么做.
I know this is wrong, and not just because it's not working, but I can't figure out how to make it right.
显然,我需要循环读取数组每个索引的所有条目的过程.我不知道该怎么做,因为我不知道在代码中应该在哪里使用索引,或者甚至是正确的开始.有一个cJSON_GetArrayItem()
,但是它只需要一个数字(可能是一个索引),而没有字符串来指示它想要的字段.
Obviously I'm going to need to loop the process of reading in all of the entries for each index of the array. I have no idea how I'm going to do that though, because I don't know where I should be using the indexes in this code, or if it is even the right start. There is a cJSON_GetArrayItem()
, but it takes only a number (presumably an index) and no string to indicate which field it wants.
推荐答案
文档中提到了parse_object().
Document mentions about parse_object().
我认为这是您需要做的.
I think this is what you need to do.
void parse_object(cJSON *root)
{
cJSON* name = NULL;
cJSON* index = NULL;
cJSON* optional = NULL;
int i;
cJSON *item = cJSON_GetObjectItem(items,"items");
for (i = 0 ; i < cJSON_GetArraySize(item) ; i++)
{
cJSON * subitem = cJSON_GetArrayItem(item, i);
name = cJSON_GetObjectItem(subitem, "name");
index = cJSON_GetObjectItem(subitem, "index");
optional = cJSON_GetObjectItem(subitem, "optional");
}
}
将此函数称为
request_json = cJSON_Parse(request_body);
parse_object(request_json);
这篇关于使用cJSON读取JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!