基于ESP8266的JSON解析实例分析

什么是JSON?

  JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。采用完全独立于编程语言的文本格式来存储和表示数据。其简洁和层次结构清晰的特点使得 JSON 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

JSON建构于两种结构:

  “名称/值”对的集合(A collection of name/value pairs)。即常说的Key/Value 键/值对。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。
值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。

eps8266的经典案例:

  这里给出一个能在esp8266上能够解析的最简单的例子:

#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"

void printJson(cJSON * root)//以递归的方式打印json的最内层键值对
{
    for(int i=0; i<cJSON_GetArraySize(root); i++)   //遍历最外层json键值对
    {
        cJSON * item = cJSON_GetArrayItem(root, i);        
        if(cJSON_Object == item->type)      //如果对应键的值仍为cJSON_Object就递归调用printJson
            printJson(item);
        else                                //值不为json对象就直接打印出键和值
        {
            printf("%s->", item->string);
            //printf("%s
", cJSON_Print(item));//内存泄漏
        }
    }
}

int main()
{
    char * jsonStr = "{"semantic":{"slots":{"name":"Charlin"}}, "rc":0, "operation":"CALL", "service":"telephone", "text":"打电话给Charlin"}";
    cJSON * root = NULL;
    cJSON * item = NULL;//cjson对象

    root = cJSON_Parse(jsonStr);     
    if (!root) 
    {
        printf("Error before: [%s]
",cJSON_GetErrorPtr());
    }
    else
    {
        printf("%s
", "有格式的方式打印Json:");           
        printf("%s

", cJSON_Print(root));//内存泄漏
        printf("%s
", "无格式方式打印json:");
        printf("%s

", cJSON_PrintUnformatted(root));//内存泄漏

        printf("%s
", "一步一步的获取name 键值对:");
        printf("%s
", "获取semantic下的cjson对象:");
        item = cJSON_GetObjectItem(root, "semantic");//
        printf("%s
", cJSON_Print(item));//内存泄漏
        printf("%s
", "获取slots下的cjson对象");
        item = cJSON_GetObjectItem(item, "slots");
        printf("%s
", cJSON_Print(item));//内存泄漏
        printf("%s
", "获取name下的cjson对象");
        item = cJSON_GetObjectItem(item, "name");
        printf("%s
", cJSON_Print(item));//内存泄漏

        printf("%s:", item->string);   //看一下cjson对象的结构体中这两个成员的意思
        printf("%s
", item->valuestring);
                        

        printf("
%s
", "打印json所有最内层键值对:");
        printJson(root);
    }
    if(root)
        cJSON_Delete(root); // 释放内存

    return 0;    
}

这里只给出一个最简单的例子:
详情咨询:(https://zhuanlan.zhihu.com/p/53730181)

顺便做个广告,本团队承接ESP8266的方案业务,有需求的朋友欢饮咨询。

原文地址:https://www.cnblogs.com/dylancao/p/12100617.html