Json 是一种数据格式,和语言无关,在什么语言中都可以使用 Json。
一般处理两方面的任务:
//test.json
{
"Name":"Ace",
"Sex":"man",
"Age":20,
"Family":{
"Father":"Gol·D·Roger",
"Mother":"Portgas·D·Rouge",
"Brother":["Sabo", "Monkey D. Luffy"]
},
"IsAlive":false,
"Comment":"yyds"
}
Json格式数据封装参考如下:Json格式数据封装
Json 字符串的解析流程和数据的封装流程相反,假设有这样一个 Json 字符串(字符串中的双引号需要通过转义字符将其转译为普通字符):
{\"name\":\"luffy\",\"sex\":\"man\",\"age\":19}
实例代码如下:
#include
#include
#include
#include "cJSON.h"
int main()
{
cJSON *json, *name, *sex, *age;
char* out="{\"name\":\"luffy\",\"sex\":\"man\",\"age\":19}";
json = cJSON_Parse(out); //解析成json形式
name = cJSON_GetObjectItem(json, "name"); //获取键值内容
sex = cJSON_GetObjectItem(json, "sex");
age = cJSON_GetObjectItem(json, "age");
printf("name:%s,sex:%s,age:%d\n", name->valuestring, sex->valuestring, age->valueint);
cJSON_Delete(json); //释放内存
}
解析一个嵌套的 Json 对象,数据如下:
{\"list\":{\"name\":\"luffy\",\"age\":19},\"other\":{\"name\":\"ace\"}}
int main()
{
char *s = "{\"list\":{\"name\":\"luffy\",\"age\":19},\"other\":{\"name\":\"ace\"}}";
cJSON *root = cJSON_Parse(s);
if(!root)
{
printf("get root faild !\n");
return -1;
}
cJSON *js_list = cJSON_GetObjectItem(root, "list");
if(!js_list)
{
printf("no list!\n");
return -1;
}
printf("list type is %d\n",js_list->type);
cJSON *name = cJSON_GetObjectItem(js_list, "name");
if(!name)
{
printf("No name !\n");
return -1;
}
printf("name type is %d\n",name->type);
printf("name is %s\n",name->valuestring);
cJSON *age = cJSON_GetObjectItem(js_list, "age");
if(!age)
{
printf("no age!\n");
return -1;
}
printf("age type is %d\n", age->type);
printf("age is %d\n",age->valueint);
cJSON *js_other = cJSON_GetObjectItem(root, "other");
if(!js_other)
{
printf("no list!\n");
return -1;
}
printf("list type is %d\n",js_other->type);
cJSON *js_name = cJSON_GetObjectItem(js_other, "name");
if(!js_name)
{
printf("No name !\n");
return -1;
}
printf("name type is %d\n",js_name->type);
printf("name is %s\n",js_name->valuestring);
if(root)
{
cJSON_Delete(root);
}
return 0;
}
打印结果:
list type is 6
name type is 4
name is luffy
age type is 3
age is 19
list type is 6
name type is 4
name is ace
Json 字符串是一个 Json 数组格式:
{\"names\":[\"luffy\",\"robin\"]}
int main(int argc, char **argv)
{
char *s = "{\"names\":[\"luffy\",\"robin\"]}";
cJSON *root = cJSON_Parse(s);
if(!root)
{
printf("get root faild !\n");
return -1;
}
cJSON *js_list = cJSON_GetObjectItem(root, "names");
if(!js_list)
{
printf("no list!\n");
return -1;
}
int array_size = cJSON_GetArraySize(js_list);
printf("array size is %d\n",array_size);
for(int i=0; i< array_size; i++)
{
cJSON *item = cJSON_GetArrayItem(js_list, i);
printf("item type is %d\n",item->type);
printf("%s\n",item->valuestring);
}
if(root)
{
cJSON_Delete(root);
}
return 0;
}
Json 对象和 Json 数组嵌套的形式,下面通过一个例子演示一下应该如何解析,字符串格式如下:
{\"list\":[{\"name\":\"luffy\",\"age\":19},{\"name\":\"sabo\",\"age\":21}]}
在解析的时候,只需要按照从属关系,一层层解析即可:
#include "cJSON.h"
#include
#include
int main(int argc, char **argv)
{
char *s = "{\"list\":[{\"name\":\"luffy\",\"age\":19},{\"name\":\"sabo\",\"age\":21}]}";
cJSON *root = cJSON_Parse(s);
if(!root)
{
printf("get root faild !\n");
return -1;
}
cJSON *list = cJSON_GetObjectItem(root, "list");
if(!list)
{
printf("no list!\n");
return -1;
}
int array_size = cJSON_GetArraySize(list);
printf("array size is %d\n",array_size);
for(int i=0; i< array_size; i++)
{
cJSON* item = cJSON_GetArrayItem(list, i);
cJSON* name = cJSON_GetObjectItem(item, "name");
printf("name is %s\n",name->valuestring);
cJSON* age = cJSON_GetObjectItem(item, "age");
printf("age is %d\n",age->valueint);
}
if(root)
{
cJSON_Delete(root);
}
return 0;
}
援引链接:添加链接描述
{
"paramz": {
"feeds": [
{
"id": 299076,
"oid": 288340,
"category": "article",
"data": {
"subject": "荔枝新闻3.0:不止是阅读",
"summary": "江苏广电旗下资讯类手机应用“荔枝新闻”于近期推出全新升级换代的3.0版。",
"cover": "/Attachs/Article/288340/3e8e2c397c70469f8845fad73aa38165_padmini.JPG",
"pic": "",
"format": "txt",
"changed": "2015-09-22 16:01:41"
}
}
],
"PageIndex": 1,
"PageSize": 20,
"TotalCount": 53521,
"TotalPage": 2677
}
}
JSONObject系统自带的解析方式解析,先来JSONObject(系统自带的类)类中的方法:
这里解析类如下:
public class JsonUtils {
/**
* 根据json数据解析返回一个List>集合
* @param json json数据
* @return
*/
public static List<HashMap<String, Object>> getJsonList(String json) {
List<HashMap<String, Object>> dataList;
dataList = new ArrayList<>();
try {
JSONObject rootObject = new JSONObject(json);
JSONObject paramzObject = rootObject.getJSONObject("paramz");
JSONArray feedsArray = paramzObject.getJSONArray("feeds");
for (int i = 0; i < feedsArray.length(); i++) {
JSONObject sonObject = feedsArray.getJSONObject(i);
JSONObject dataObject = sonObject.getJSONObject("data");
String subjectStr = dataObject.getString("subject");
String summaryStr = dataObject.getString("summary");
String coverStr = dataObject.getString("cover");
HashMap<String, Object> map = new HashMap<>();
map.put("subject", subjectStr);
map.put("summary", summaryStr);
map.put("cover", coverStr);
dataList.add(map);
}
return dataList;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
此方法写起来主要是比较费时间,就是几个方法不停的调用。
void MainWindow::writeJson()
{
QJsonObject obj;
obj.insert("Name", "Ace");
obj.insert("Sex", "man");
obj.insert("Age", 20);
QJsonObject subObj;
subObj.insert("Father", "Gol·D·Roger");
subObj.insert("Mother", "Portgas·D·Rouge");
QJsonArray array;
array.append("Sabo");
array.append("Monkey D. Luffy");
subObj.insert("Brother", array);
obj.insert("Family", subObj);
obj.insert("IsAlive", false);
obj.insert("Comment", "yyds");
QJsonDocument doc(obj);
QByteArray json = doc.toJson();
QFile file("D:/Qt/QTT/AI/TcpServer/ace.json");
file.open(QFile::WriteOnly);
file.write(json);
file.close();
}
void MainWindow::readJson()
{
QFile file("D:/Qt/QTT/AI/TcpServer/ace.json");
file.open(QFile::ReadOnly);
QByteArray json = file.readAll();
file.close();
QJsonDocument doc = QJsonDocument::fromJson(json);
if(doc.isObject())
{
QJsonObject obj = doc.object();
QStringList keys = obj.keys();
for(int i=0; i<keys.size(); ++i)
{
QString key = keys.at(i);
QJsonValue value = obj.value(key);
if(value.isBool())
{
qDebug() << key << ":" << value.toBool();
}
if(value.isString())
{
qDebug() << key << ":" << value.toString();
}
if(value.isDouble())
{
qDebug() << key << ":" << value.toInt();
}
if(value.isObject())
{
qDebug()<< key << ":";
// 直接处理内部键值对, 不再进行类型判断的演示
QJsonObject subObj = value.toObject();
QStringList ls = subObj.keys();
for(int i=0; i<ls.size(); ++i)
{
QJsonValue subVal = subObj.value(ls.at(i));
if(subVal.isString())
{
qDebug() << " " << ls.at(i) << ":" << subVal.toString();
}
if(subVal.isArray())
{
QJsonArray array = subVal.toArray();
qDebug() << " " << ls.at(i) << ":";
for(int j=0; j<array.size(); ++j)
{
// 因为知道数组内部全部为字符串, 不再对元素类型进行判断
qDebug() << " " << array[j].toString();
}
}
}
}
}
}
}
测试结果如下: