首先要在esp_iot_sdk/example/IoT_Demo示例目录下找到user_json.c和user_json.h,把这两个文件包含进自己的工程。
下面给出生成Json树的示例,生成的JSON树get_h内容如下:"hi":{"hello":"world"}
/***************************************************/ LOCAL int ICACHE_FLASH_ATTR hello_get(struct jsontree_context *js_ctx) { const char *path = jsontree_path_name(js_ctx, js_ctx->depth - 1); char string[32]; if (os_strncmp(path, "hello", 5) == 0) { os_sprintf(string, "world"); } jsontree_write_string(js_ctx, string); return 0; } LOCAL struct jsontree_callback hello_callback = JSONTREE_CALLBACK(hello_get, NULL); JSONTREE_OBJECT(get_hello, JSONTREE_PAIR("hello", &hello_callback)); JSONTREE_OBJECT(get_h, JSONTREE_PAIR("hi", &get_hello));
其中宏定义JSONTREE_OBJECT是生成一个JSON数的对象,第一个参数是该对象的名称(get_h),JSONTREE_PAIR是生成一个键值对的宏。
JSONTREE_CALLBACL是生成一个回调指针的宏,该宏有两个参数,第一个参数是设置读取JSON树的值的函数,这里为hello_get函数,第二个参数是设置写入JSON树的值的函数,这里没有用到,为NULL。
hello_get是读取JSON树的值的函数。其中用os_strncnp进行JSON键的判断,这里示例是:如果键值为"hello",则获取的值为"world"。
#define BUF_LENTH 64 LOCAL char buf[BUF_LENTH]; json_ws_send((struct jsontree_value *)&get_h, "hi", buf); os_printf("%s\n",buf);
最后打印结果是:
{
"hello":"world"
}
下面是一个生成温湿度的例程:
/********************DHT11***********************/ LOCAL int ICACHE_FLASH_ATTR dht11_get(struct jsontree_context *js_ctx) { const char *path = jsontree_path_name(js_ctx, js_ctx->depth - 1); char string[32]; if (os_strncmp(path, "temp", 4) == 0) { //os_sprintf(string, "%d",temperture); os_sprintf(string,"25"); } else if(os_strncmp(path, "hum", 3) == 0) { //os_sprintf(string, "%d",hum); os_sprintf(string,"40"); } jsontree_write_string(js_ctx, string); return 0; } LOCAL struct jsontree_callback dht11_callback = JSONTREE_CALLBACK(dht11_get, NULL); JSONTREE_OBJECT(get_dht11, JSONTREE_PAIR("temp", &dht11_callback), JSONTREE_PAIR("hum", &dht11_callback)); JSONTREE_OBJECT(DHT11JSON, JSONTREE_PAIR("dht11", &get_dht11)); //返回DHT11数据的json格式 char* ICACHE_FLASH_ATTR get_dht11_json(void) { LOCAL char dht11_buf[64]; os_memset(dht11_buf,0,64); //清空 json_ws_send((struct jsontree_value *)&DHT11JSON, "dht11", dht11_buf); return dht11_buf; }
os_printf(get_dht11_json());
{
"temp":"25",
"hum":"40"
}