Json概念与cJson使用
1.Json是什么
Json:JacaScript Object Notation,JSON 语法是 JavaScript 语法的子集。
是一种键值对的文本协议,普遍用于传输一些数据流,因为在不同语言中使用较为广泛,都有不同的开源库支持。
举一个Json的例子:
{
"title":"JSON Example",
"author": {
"name":"John Doe",
"age": 35,
"isVerified":true
},
"tags":["json", "syntax", "example"],
"rating": 4.5,
"isPublished":false,
"comments": null
}
Json有两种数据结构,一种为使用{}
的"对象",另一种为使用[]
的数组。
- 对象:使用{}内包含的为内容的对象,每个对象由一组“键-值”对应,“键”一般为字符串,“值”可以为字符串或数字;每两个键值对之间用逗号隔开,最后一组键值对可不加逗号。
- 数组:表示并列关系,内容可以是字符串、数字,类似C语言中数组。
注:
在实际使用中注意用
\
来转义字符。
2.cJson的使用
cJson的github托管地址为:https://github.com/DaveGamble/cJSON
其核心内容为cJSON.c与cJSON.h两个文件,有较好的移植性。
2.1 解析Json文本
#include <stdio.h>
#include "cJSON.h"
int main(int argc, char **argv)
{
char *str = " \
{ \
\"title\":\"JSON Example\", \
\"author\": { \
\"name\":\"John Doe\", \
\"age\": 35, \
\"isVerified\":true \
}, \
\"tags\":[\"json\", \"syntax\", \"example\"], \
\"rating\": 4.5, \
\"isPublished\":false, \
\"comments\": null \
}";
cJSON *json;
json = cJSON_Parse(str);
if (!json)
{
printf("cJSON_Parse err\n");
return 0;
}
cJSON *author = cJSON_GetObjectItem(json, "author");
cJSON *age = cJSON_GetObjectItem(author, "age");
if (age)
{
printf("age = %d\n", age->valueint);
}
cJSON *tags = cJSON_GetObjectItem(json, "tags");
cJSON *item = cJSON_GetArrayItem(tags, 2);
if (item)
{
printf("item = %s\n", item->valuestring);
}
return 0;
}
2.2 构建Json文本
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main()
{
// 创建根对象
cJSON *root = cJSON_CreateObject();
// 添加 title 字段
cJSON_AddStringToObject(root, "title", "JSON Example");
// 创建 author 对象
cJSON *author = cJSON_CreateObject();
cJSON_AddStringToObject(author, "name", "John Doe");
cJSON_AddNumberToObject(author, "age", 35);
cJSON_AddBoolToObject(author, "isVerified", 1); // true
cJSON_AddItemToObject(root, "author", author);
// 添加 tags 数组
cJSON *tags = cJSON_CreateArray();
cJSON_AddItemToArray(tags, cJSON_CreateString("json"));
cJSON_AddItemToArray(tags, cJSON_CreateString("syntax"));
cJSON_AddItemToArray(tags, cJSON_CreateString("example"));
cJSON_AddItemToObject(root, "tags", tags);
// 添加其他字段
cJSON_AddNumberToObject(root, "rating", 4.5);
cJSON_AddBoolToObject(root, "isPublished", 0); // false
cJSON_AddNullToObject(root, "comments");
// 打印 JSON 字符串
char *jsonString = cJSON_Print(root);
printf("%s\n", jsonString);
// 释放内存
free(jsonString);
cJSON_Delete(root);
return 0;
}