10

我正在尝试解析一个 json 数组,我遇到了问题。

我的数组是这样的:

configure: {
  "id": 4,
  "userId": 107,
  "deviceMacAddress": "00:06:66:30:02:3C",
  "medication": [{
    "id": 11,
    "version": 18,
    "name": "name1",
    "unit": "mg",
    "forMed": "for1",
    "schedule": [1]
  }, {
  "id": 45,
  "version": 1,
  "name": "sdga",,
  "unit": "mg",
  "forMed": "54234",
  "schedule": [0,1,2,3,4,5,6]
  }],

我能够访问药物阵列并打印总阵列,但无法访问阵列内的对象。您能否建议使用 C 语言执行此操作的任何解决方案或示例?

我的代码

int main(int argc, char **argv) {
  struct json_object *med_obj, *medi_obj, *tmp1_obj;
  struct array_list *lArray;
  charname[10] = {0};
  static const char filename[] = "xyz.txt";
  med_obj = json_object_from_file(filename);
  medi_obj = json_object_object_get(med_obj, "medication");
  lArray = json_object_get_array(medi_obj);
  tmp1_obj = json_object_object_get(medi_obj, "name");
  strcpy (name,json_object_to_json_string(tmp1_obj));
  printf("name=%s\n",name);
}

问候,列宁。

4

3 回答 3

21

您需要使用json_object *变量访问内部数组。

试试这个:

struct json_object *med_obj, *medi_array, *medi_array_obj, *medi_array_obj_name;
int arraylen, i;
charname[10] = {0};
static const char filename[] = "xyz.txt";
med_obj = json_object_from_file(filename);
medi_array = json_object_object_get(med_obj, "medication");

// medi_array is an array of objects
arraylen = json_object_array_length(medi_array);

for (i = 0; i < arraylen; i++) {
  // get the i-th object in medi_array
  medi_array_obj = json_object_array_get_idx(medi_array, i);
  // get the name attribute in the i-th object
  medi_array_obj_name = json_object_object_get(medi_array_obj, "name");
  // print out the name attribute
  printf("name=%s\n", json_object_get_string(medi_array_obj_name));
}
于 2013-06-07T05:17:13.550 回答
0

您可以使用 jsoncpp 来完成这项工作。数组作为 Json::Value,你可以

medicationValue = jsonObject[medicationKey];
Json::Value::Members member;
member = medicationValue .getMemberNames();

for (Json::Value::Members::iterator iter = member.begin(); iter != member.end(); iter++) {
    the element of medication here
}

我希望能帮助你。

于 2013-06-07T04:01:29.777 回答
0

如果要将数组作为 json 对象访问,则应将其作为 json_object* 而不是 array_list*

struct json_object *lArray; 
...
lArray=json_object_get(medi_obj); 
tmp1_obj = json_object_object_get(json_object_array_get_idx(lArray, 0), "name");
于 2013-06-07T04:54:44.143 回答