【问题标题】:parse json arrays using cJSON library使用 cJSON 库解析 json 数组
【发布时间】:2014-06-15 16:39:43
【问题描述】:

首先,这是一个非常广泛的问题,当我要求社区为我编写代码时可能会遇到这个问题。这不是我的意图,但我很迷茫,我不知道如何提供足够的信息。

我正在尝试使用 Dave Gamble 编写的 cJSON 库, 我发现这对于用于我的嵌入式设备进行 JSON 解析和组合非常有用。

读取以下 JSON 数组

{ 
 "name": "Jack", 
  "types":[23,56,78],
 "format": {
 "type": "rect",
  "width": 1920, } 
}

.. 并使用此方法解析获取对象

  cJSON *format = cJSON_GetObjectItem(json,"format");

  int framerate = cJSON_GetObjectItem(format,"width")->valueint; 

但我无法解析键“名称”和对象简单键值,

我试过了

  cJSON *array = cJSON_GetArrayItem(json,"types"); 

  int value = cJSON_GetArrayItem(format1,1)->valueint;

但是没用,怎么解析数组对象和简单的key值..

【问题讨论】:

标签: c json cjson


【解决方案1】:

你的 json 很好。您可以遍历 cJSON 中的值数组:

cJSON * array = cJSON_GetObjectItem(json, "types");
for (i = 0 ; i < cJSON_GetArraySize(array) ; i++)
{
    printf("%d ",cJSON_GetArrayItem(array, i)->valueint);
}

将打印

23 56 78

【讨论】:

    【解决方案2】:

    我认为 JSON 元素应该尊重 key:value 格式。

    { 
     "name": "Jack", 
      "types":[{"type" : 23}, {"type" : 56}, {"type":78}],
     "format": {
     "type": "rect",
      "width": 1920, } 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 2021-07-24
      • 1970-01-01
      相关资源
      最近更新 更多