【STM32】使用keil提供的JSON库——Jansson
char *buf;
json_t *root = json_pack("{s:i}","hello",12);
buf = json_dumps(root, JSON_ENCODE_ANY);
if(buf != NULL)
{
printf("\n\n\nout:%s\r\n", buf);
}
else
{
printf("Json Dumps ERROR !!!\r\n");
}
//Note that the requested space must be freed
json_delete(root);
free(buf);
int beep;
char buf[20] = {"{\“beep\”:0}"};
json_error_t error;
json_t *root = json_loads( buf, JSON_REJECT_DUPLICATES, &error );
if (!root )
{
printf( "Json error: on line %d: %s\n", error.line, error.text );
}
else
{
TOS_ASSERT(json_is_object( root ));
json_unpack(root, "{s:b}","beep", &beep);
json_delete(root);
}
限定符 | 说明 |
---|---|
s | 将null结尾的UTF-8字符串转换为JSON字符串 |
s? | 和上面类似,但是如果位置参数是NULL则插入JSON null值 |
s# | 对应两个位置参数const char *, int,将指定长度的UTF-8缓冲转换为JSON字符串 |
s% | 和上面类似,只是未知参数类型为const char *, size_t |
+ | 把此位置参数连接到前一个位置参数后面 |
+# | 和上面类似,接收位置参数const char *, int |
+% | 和上面类似,接收位置参数const char *, size_t |
n | 输出null,不消耗位置参数 |
b | 转换int为JSON布尔值 |
i | 转换int为JSON整数 |
I | 转换json_int_t为JSON整数 |
f | 转换double为JSON实数 |
o | 原样插入json_t*结构 |
O | 和上面类似,但是目标json_t的引用计数会增加 |
o? o? | 类似上面两个,但是当位置参数为NULL时插入null |
[fmt] | 使用内部的格式限定符构建一个JSON数组,fmt可以是任意符合要求的格式限定符序列 |
{fmt} | 使用内部的格式限定符构建一个JSON对象,fmt可以是任意符合要求的格式限定符序列 |
/* root is the JSON integer 42 */
int myint;
json_unpack(root, "i", &myint);
assert(myint == 42);
/* root is the JSON object {"foo": "bar", "quux": true} */
const char *str;
int boolean;
json_unpack(root, "{s:s, s:b}", "foo", &str, "quux", &boolean);
assert(strcmp(str, "bar") == 0 && boolean == 1);
/* root is the JSON array [[1, 2], {"baz": null} */
json_error_t error;
json_unpack_ex(root, &error, JSON_VALIDATE_ONLY, "[[i,i], {s:n}]", "baz");
/* returns 0 for validation success, nothing is extracted */
/* root is the JSON array [1, 2, 3, 4, 5] */
int myint1, myint2;
json_unpack(root, "[ii!]", &myint1, &myint2);
/* returns -1 for failed validation */
/* root is an empty JSON object */
int myint = 0, myint2 = 0, myint3 = 0;
json_unpack(root, "{s?i, s?[ii]}",
"foo", &myint1,
"bar", &myint2, &myint3);
/* myint1, myint2 or myint3 is no touched as "foo" and "bar" don't exist */
/* Build an empty JSON object */
json_pack("{}");
/* Build the JSON object {"foo": 42, "bar": 7} */
json_pack("{sisi}", "foo", 42, "bar", 7);
/* Like above, ':', ',' and whitespace are ignored */
json_pack("{s:i, s:i}", "foo", 42, "bar", 7);
/* Build the JSON array [[1, 2], {"cool": true}] */
json_pack("[[i,i],{s:b}]", 1, 2, "cool", 1);
/* Build a string from a non-null terminated buffer */
char buffer[4] = {'t', 'e', 's', 't'};
json_pack("s#", buffer, 4);
/* Concatenate strings together to build the JSON string "foobarbaz" */
json_pack("s++", "foo", "bar", "baz");
/* Create an empty object or array when optional members are missing */
json_pack("{s:s*,s:o*,s:O*}", "foo", NULL, "bar", NULL, "baz", NULL);
json_pack("[s*,o*,O*]", NULL, NULL, NULL);
参考:
1.STM32 Jansson解析json
2.使用keil提供的JSON库——Jansson 在V5上移植