通过CJson库要能完成如下的任务:
1、可以对字符串(json格式)进行解析
3、可以对指定的key进行赋值
{
char phyattr_mem[][64] = {"tx_crc","mode","link","end_of_list"};
char actual_phyattr[] = "{\"tx_crc\":\"0\",\"mode\":\"1\"}";
char actual_phyattr[] = "{\"tx_crc\":\"0\",\"mode\":\"1\"}";
\*需要对解析解析出错做处理*\
cJSON *actual = cJSON_Parse(actual_phyattr);
cJSON *root = cJSON_CreateObject(); int i = 0; while (0!=strcmp(phyattr_mem[i],"end_of_list")) { cJSON *tmp = cJSON_GetObjectItem(actual,phyattr_mem[i]); if (NULL == tmp) //返回列表中找不到属性名 { cJSON_AddStringToObject(root,phyattr_mem[i],"NA"); } else { char *val_str = tmp->valuestring; cJSON_AddStringToObject(root,val_str); } ++i; } char *phyattr = cJSON_PrintUnformatted(root); printf("%s\n",phyattr); cJSON_Delete(root); cJSON_Delete(actual); return 0; }