QtJson用法

序列化:
 1 QtJson::JsonObject friend1, friend2, friend3;
 2 friend1["id"] = 1;
 3 friend1["name"] = "Mackenzie Hamphrey";
 4 
 5 friend2["id"] = 2;
 6 friend2["name"] = "Melanie Molligan";
 7 
 8 friend3["id"] = 3;
 9 friend3["name"] = "Sydney Calhoun";
10 
11 QtJson::JsonArray friends;
12 friends.append(friend1);
13 friends.append(friend2);
14 friends.append(friend3);
15 
16 QtJson::JsonObject obj;
17 obj["friends"] = friends;

反序列化

 1 #include "json.h"
 2 
 3 bool ok;
 4 // json is a QString containing the JSON data
 5 QtJson::JsonObject result = QtJson::parse(json, ok).toMap();
 6 
 7 if(!ok) {
 8   qFatal("An error occurred during parsing");
 9 
10 qDebug() << "encoding:" << result["encoding"].toString();
11 qDebug() << "plugins:";
12 
13 foreach(QVariant plugin, result["plug-ins"].toList()) {
14     qDebug() << "  -" << plugin.toString();
15 }
16 
17 QtJson::JsonObject nested = result["indent"].toMap();
18 qDebug() << "length:" << nested["length"].toInt();
19 qDebug() << "use_space:" << nested["use_space"].toBool();

 

posted @ 2015-11-29 23:46  凤梨罐头  阅读(267)  评论(0编辑  收藏  举报