cJSON: 一个用c写的一个简单好用的JSON解析器
实例1: 创建一个简单的学生信息数组
解析json字符串
cJson源码:cjson
实例1: 创建一个简单的学生信息数组
cJSON* pRoot = cJSON_CreateObject(); cJSON* pArray = cJSON_CreateArray(); cJSON_AddItemToObject(pRoot, "students_info", pArray); char* szOut = cJSON_Print(pRoot); cJSON* pItem = cJSON_CreateObject(); cJSON_AddStringToObject(pItem, "name", "chenzhongjing"); cJSON_AddStringToObject(pItem, "sex", "male"); cJSON_AddNumberToObject(pItem, "age", 28); cJSON_AddItemToArray(pArray, pItem); pItem = cJSON_CreateObject(); cJSON_AddStringToObject(pItem, "name", "fengxuan"); cJSON_AddStringToObject(pItem, "sex", "male"); cJSON_AddNumberToObject(pItem, "age", 24); cJSON_AddItemToArray(pArray, pItem); pItem = cJSON_CreateObject(); cJSON_AddStringToObject(pItem, "name", "tuhui"); cJSON_AddStringToObject(pItem, "sex", "male"); cJSON_AddNumberToObject(pItem, "age", 22); cJSON_AddItemToArray(pArray, pItem); char* szJSON = cJSON_Print(pRoot); cJSON_Delete(pRoot); //free(szJSON); pRoot = cJSON_Parse(szJSON); pArray = cJSON_GetObjectItem(pRoot, "students_info"); if (NULL == pArray) { return -1; } int iCount = cJSON_GetArraySize(pArray); for (int i = 0; i < iCount; ++i) { cJSON* pItem = cJSON_GetArrayItem(pArray, i); if (NULL == pItem) { continue; } string strName = cJSON_GetObjectItem(pItem, "name")->valuestring; string strSex = cJSON_GetObjectItem(pItem, "sex")->valuestring; int iAge = cJSON_GetObjectItem(pItem, "age")->valueint; } cJSON_Delete(pRoot); free(szJSON);
解析json字符串
char* json = "{\"action\":{\"state\":3,\"data\":\"Hello\"}}"; cJSON *root; cJSON *format; int value_int; char *value_string; root = cJSON_Parse(json); format = cJSON_GetObjectItem(root,"action"); value_int = cJSON_GetObjectItem(format,"state")->valueint; value_string = cJSON_GetObjectItem(format,"data")->valuestring; cJSON_Delete(root);
cJson源码:cjson
收藏的用户(0) X
正在加载信息~
推荐阅读
最新回复 (0)
站点信息
- 文章2305
- 用户1336
- 访客11363573
每日一句
Same actions bring same results.
重复旧行为,只会得到旧结果。
重复旧行为,只会得到旧结果。
新会员