一、 json相关API
mongoose 开源库可以使用json进行数据处理。
①创建json字符串
// A helper macro for printing JSON: mg_snprintf(buf, len, "%m", MG_ESC("hi"))
#define MG_ESC(str) mg_print_esc, 0, (str)
char *mg_mprintf(const char *fmt, ...);
// Print message into an allocated memory buffer.
// Caller must free the result.
示例:
char *json = mg_mprintf("{%m:%d}", MG_ESC("name"), 123);
free(json);
json相关api,如下图;
②获取double类型数值
bool mg_json_get_num(struct mg_str json, const char *path, double *v);
③获取bool类型
bool mg_json_get_bool(struct mg_str json, const char *path, bool *v);
④获取整形数值
long mg_json_get_long(struct mg_str json, const char *path, long default_val);
⑤获取字符串类型
char *mg_json_get_str(struct mg_str json, const char *path);
详细介绍,可参考官方网址:
https://mongoose.ws/documentation/#json
二、代码测试
功能,创建json字符串,并解析,json字符串如下:
a json string: {"name":"haha","age":18,"b": [12, 2.30000],"a":1.23000}
代码如下:
#include "mongoose.h"
int main(int argc, char *argv[])
{
char *buf = mg_mprintf("{%m:%m,%m:%d,%m: [%d, %f],%m:%f}", MG_ESC("name"),MG_ESC("haha"), MG_ESC("age"),18,MG_ESC("b"), 12,2.3,MG_ESC("a"),1.23);
printf("json=%s\n",buf);
struct mg_str json=mg_str(buf);
char *str = mg_json_get_str(json, "$.name");
printf("name=%s\n",str);
free(str);
long num = mg_json_get_long(json, "$.age", -1); // num = -1
printf("age=%d\n",num);
long b0 = mg_json_get_long(json, "$.b[0]", -1) ;
printf("b0=%d\n",b0);
double b1 =0.0;
mg_json_get_num(json, "$.b[1]", &b1) ;
printf("b1=%f\n",b1);
double d = 0.0;
mg_json_get_num(json, "$.a", &d);
printf("d=%f\n",d);
free(buf);
return 0;
}
测试结果:
欢迎关注公众号:嵌入式学习与实践