Chinaunix首页 | 论坛 | 博客
  • 博客访问: 347543
  • 博文数量: 100
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 521
  • 用 户 组: 普通用户
  • 注册时间: 2014-10-31 11:37
个人简介

活到老,学到老

文章分类

全部博文(100)

文章存档

2018年(1)

2017年(2)

2016年(11)

2015年(82)

2014年(4)

我的朋友

分类: C/C++

2016-08-13 11:18:08

json:
  1. {
  2.     "test": {
  3.         "test1": {
  4.             "a": 1,
  5.             "b": 2,
  6.             "c": 3
  7.         },
  8.          "test2": [4, 5, 6]
  9.       }
  10. }

代码:
  1. 解析
  2. bool decodeJson(string jsonPath)
    {
    FILE *fp = fopen(jsonPath.c_str(), "r");
    fseek(fp, 0, SEEK_END);
    long len = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    char *data = (char*)malloc(len + 1);
    fread(data, 1, len, fp);
    fclose(fp);


    cJSON *root_json = cJSON_Parse(data);
    if (NULL == root_json)
    {
    cout << cJSON_GetErrorPtr();
    cJSON_Delete(root_json);
    return false;
    }


    cJSON *test_json = cJSON_GetObjectItem(root_json, "test");


    cJSON *test1_json = cJSON_GetObjectItem(test_json, "test1");
    cJSON *temp = test1_json->child;
    while (temp != NULL)
    {
    cout< temp = temp->next;
    }


    cJSON *test2_array = cJSON_GetObjectItem(test_json, "test2");
    int test2ArraySize = cJSON_GetArraySize(test2_array);
    for (int i = 0; i < test2ArraySize; i++)
    {
    char *ch = cJSON_Print(cJSON_GetArrayItem(test2_array, i));
    cout << string(ch);
    free(ch);
    }
    cJSON_Delete(root_json);
    cout << endl;
    return true;
    }

    #生成
    bool codeJson(string jsonPath)
    {
    cJSON *root_json,*test_json, *test1_json, *test2_array;


    test1_json = cJSON_CreateObject();
    cJSON_AddNumberToObject(test1_json, "a", 1);
    cJSON_AddNumberToObject(test1_json, "b", 2);
    cJSON_AddNumberToObject(test1_json, "c", 3);
    test2_array = cJSON_CreateArray();
    for (int i = 4; i <= 6; i++ )
    {
    cJSON_AddItemToArray(test2_array, cJSON_CreateNumber(i));
    }


    test_json = cJSON_CreateObject();
    cJSON_AddItemToObject(test_json, "test1", test1_json);
    cJSON_AddItemToObject(test_json, "test2", test2_array);


    root_json = cJSON_CreateObject();
    cJSON_AddItemToObject(root_json, "test", test_json);


    cout << string(cJSON_Print(root_json));
    FILE *fp = fopen(jsonPath.c_str(), "w");
    fputs(cJSON_Print(root_json), fp);
    fclose(fp);
    cJSON_Delete(root_json);
    return true;
    }



阅读(1471) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~