esp8266的JSON解析 学习
首先是基于esp8266的json解析
之前我已经会去获取天气信息,然后现在专门解析json
我现在用的是CJSON 的包
基于esp8266改动后的
解析知心天气返回的天气信息的json数据
{
"results": [{
"location": {
"id": "WX4FBXXFKExx",//id 自己去获取
"name": "Beijing",
"country": "CN",
"path": "Beijing,Beijing,China",
"timezone": "Asia/Shanghai",
"timezone_offset": "+08:00"
},
"now": {
"text": "Sunny",
"code": "0",
"temperature": "27"
},
"last_update": "2020-05-19T11:31:00+08:00"
}]
}
分析下。他数据包在数组里面,一开始还要解析数组,然后数组里面还有子json
子json 1 "location"
子json 2"now":
解析代码讲解
void ICACHE_FLASH_ATTR parseJson(void)
{
u8* jsonRoot ="{\"results\":[{\"location\":{\"id\":\"WS11R8SX9PXX\",\"name\":\"Longgang\",\"country\":\"CN\",\"path\":\"Longgang,Shenzhen,Guangdong,China\",\"timezone\":\"Asia/Shanghai\",\"timezone_offset\":\"+08:00\"},\"now\":{\"text\":\"Cloudy\",\"code\":\"4\",\"temperature\":\"31\"},\"last_update\":\"2020-05-19T16:10:00+08:00\"}]}";
cJSON *pJsonRoot = cJSON_Parse(jsonRoot);//把他从字符串格式转换成json格式 如果是正确的格式转换成功,如果不是返回NULL
if (pJsonRoot !=NULL) {
char *s = cJSON_Print(pJsonRoot);//转换成cjson格式//格式化 为了输出好看
//os_printf("%s\r\n", s);//打印出来
// cJSON_free((void *) s);//用完之后要释放 字符串输出用的
cJSON *pArry = cJSON_GetObjectItem(pJsonRoot, "results");//数组里面的 因为他用数组包住了,但是里面有只有一个数据,所以先这样
if (pArry) {
int arryLength = cJSON_GetArraySize(pArry);
os_printf("get arryLength : %d \n", arryLength);
cJSON *Child_node=cJSON_GetArrayItem(pArry, 0);//获取数组里面的子json 获取到的就是jso格式的
if (Child_node !=NULL)
{
cJSON *location = cJSON_GetObjectItem(Child_node,"location");//获取到了子json
if(location)//location子JSON里面的
{
cJSON *Child_id = cJSON_GetObjectItem(location,"id");
if(Child_id)
{
os_printf("get id: %s \n", Child_id->valuestring);
}
cJSON *Child_name = cJSON_GetObjectItem(location,"name");
if(Child_name)
{
if (cJSON_IsString(Child_name))//判断下是不是字符串 看他是不是字符串格式
{
os_printf("get name: %s \n", Child_name->valuestring);
}
}
cJSON *Child_country = cJSON_GetObjectItem(location,"country");
if(Child_country)
{
if (cJSON_IsString(Child_country))//判断下是不是字符串
{
os_printf("get country : %s \n", Child_country->valuestring);
}
}
cJSON *Child_path = cJSON_GetObjectItem(location,"path");
if(Child_path)
{
if (cJSON_IsString(Child_path))//判断下是不是字符串
{
os_printf("get path : %s \n", Child_path->valuestring);
}
}
}
cJSON *now = cJSON_GetObjectItem(Child_node,"now");//获取到了子json
if(now)
{
cJSON *text = cJSON_GetObjectItem(now,"text");//获取到了子json
if(text)
{
if (cJSON_IsString(text))//判断下是不是字符串
{
os_printf("get text : %s \n", text->valuestring);
}
}
cJSON *code = cJSON_GetObjectItem(now,"code");//获取到了子json
if(text)
{
if (cJSON_IsString(code))//判断下是不是字符串
{
os_printf("get code : %s \n", code->valuestring);
}
}
cJSON *temperature = cJSON_GetObjectItem(now,"temperature");//获取到了子json
if(temperature)
{
if (cJSON_IsString(temperature))//判断下是不是字符串
{
os_printf("get temperature : %s \n", temperature->valuestring);
}
}
}
}
}
}
cJSON_Delete(pJsonRoot);//释放 那些子json 不用释放,,我刚释放,发现就出问题了。所以值需要释放一次总的
}
json里面包含了json数据,里面 的子json,不用另外释放
cJSON_Print(ADDS); 需要用一个指针装起来,没调用一次,会分配一次内存