使用cjson过程中,有的时候只需要更新整个json对象中的部分数据,cjson中提供了这样的接口,针对以下两个接口,给出使用示例。
CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
一、更新键值
数据示例
源数据:
{
"Message": {
"Command": "Read"
},
"Type": "int"
}
更新后数据:
{
"Message": {
"Result": "Err"
},
"Type": "char"
}
一共两个数据类型的更新,一个是针对键值对的更新,比如把Type的值由int改为char。另一个是针对json对象的更新,如Message节点中,整个大括号里面所有数据的更新。代码如下:
int My_UpdateJsonData(char* string)
{
printf("jsonroot : \n%s\n", string);
cJSON* str_root = cJSON_Parse(string);
char* cjson_str = cJSON_Print(str_root);
printf("\n%s\n", cjson_str);
free(cjson_str);
//更新Type的值
cJSON_ReplaceItemInObject(str_root, "Type", cJSON_CreateString("char"));
cJSON * ObjMsg = cJSON_CreateObject();
cJSON_AddStringToObject(ObjMsg, "Result", "Err");
//更新Message的值
cJSON_ReplaceItemInObject(str_root, "Message", ObjMsg);
cjson_str = cJSON_Print(str_root);
printf("replace:\n%s\n", cjson_str);
free(cjson_str);
cJSON_Delete(str_root);
return 0;
}
int main()
{
int nRtn = 0;
char abyBuf[1024] = "{\"Message\":{\"Command\":\"Read\"},\"Type\":\"int\"}";
My_UpdateJsonData(abyBuf);
return nRtn;
}
要注意,针对键值对的更新中,第三个参数不能直接以字符串或者数字赋值,必须调用cjson的接口,生成对象数据。
cJSON_ReplaceItemInObject(str_root, "Type", cJSON_CreateString("char"));
对应接口如下:
/* These calls create a cJSON item of the appropriate type. */
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
二、数组元素更新
数据示例
{
"DataArr": [[1, 2], [3, 4], [5, 6]]
}
{
"DataArr": [[1, 2], [1, 2, 3, 4], [5, 6]]
}
修改数组中元素,因为数组中的元素可能有多种,其他类型应该也是类似的。代码如下:
int My_UpdateJsonArrData(char* string)
{
printf("jsonroot : \n%s\n", string);
cJSON* str_root = cJSON_Parse(string);
char* cjson_str = cJSON_Print(str_root);
printf("\n%s\n", cjson_str);
free(cjson_str);
const int anNum[4] = {1, 2, 3, 4};
//新建一个JSON数组,每个元素是int型数据,整个数组是一个json对象
cJSON * ArrNum = cJSON_CreateIntArray(anNum, 4);
cJSON * DataArr = cJSON_GetObjectItem(str_root,"DataArr");
//更新DataArr第1元素
cJSON_ReplaceItemInArray(DataArr, 1, ArrNum);
cjson_str = cJSON_Print(str_root);
printf("replace:\n%s\n", cjson_str);
free(cjson_str);
cJSON_Delete(str_root);
return 0;
}
int main()
{
int nRtn = 0;
char abyBuf[1024] = "{\"DataArr\":[[1,2],[3,4],[5,6]]}";
My_UpdateJsonArrData(abyBuf);
return nRtn;
}
用到的接口是
cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
array: 要更改的外层数组
which: 数组的索引
newitem:新的元素对象