Chinaunix首页 | 论坛 | 博客

OS

  • 博客访问: 2218708
  • 博文数量: 691
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2660
  • 用 户 组: 普通用户
  • 注册时间: 2014-04-05 12:49
个人简介

不浮躁

文章分类

全部博文(691)

文章存档

2019年(1)

2017年(12)

2016年(99)

2015年(207)

2014年(372)

分类: 嵌入式

2015-11-27 11:40:07

原文地址: QJsonDocument 处理 JSON 作者:luozhiyong131

Qt5 新增加了处理 JSON 的类,与 XML 类库类似,均以 QJson 开头,Qt5 新增加六个相关类:

QJsonArray

封装 JSON 数组

QJsonDocument

读写 JSON 文档

QJsonObject

封装 JSON 对象

QJsonObject::iterator

用于遍历QJsonObject的 STL 风格的非 const 遍历器

QJsonParseError

报告 JSON 处理过程中出现的错误

QJsonValue

封装 JSON 

使用示例:

点击(此处)折叠或打开

  1. QString json("{"
  2.         "\"encoding\" : \"UTF-8\","
  3.         "\"plug-ins\" : ["
  4.         "\"python\","
  5.         "\"c++\","
  6.         "\"ruby\""
  7.         "],"
  8.         "\"indent\" : { \"length\" : 3, \"use_space\" : true }"
  9.         "}");
  10. QJsonParseError error;
  11. QJsonDocument jsonDocument = QJsonDocument::fromJson(json.toUtf8(), &error);
  12. if (error.error == QJsonParseError::NoError) {
  13.     if (jsonDocument.isObject()) {
  14.         QVariantMap result = jsonDocument.toVariant().toMap();
  15.         qDebug() << "encoding:" << result["encoding"].toString();
  16.         qDebug() << "plugins:";

  17.         foreach (QVariant plugin, result["plug-ins"].toList()) {
  18.             qDebug() << "\t-" << plugin.toString();
  19.         }

  20.         QVariantMap nestedMap = result["indent"].toMap();
  21.         qDebug() << "length:" << nestedMap["length"].toInt();
  22.         qDebug() << "use_space:" << nestedMap["use_space"].toBool();
  23.     }
  24. } else {
  25.     qFatal(error.errorString().toUtf8().constData());
  26.     exit(1);
  27. }

如果需要使用QJsonDocument处理 JSON 文档,我们只需要使用下面的代码模板

点击(此处)折叠或打开

  1. // 1. 创建 QJsonParseError 对象,用来获取解析结果
  2. QJsonParseError error;
  3. // 2. 使用静态函数获取 QJsonDocument 对象
  4. QJsonDocument jsonDocument = QJsonDocument::fromJson(json.toUtf8(), &error);
  5. // 3. 根据解析结果进行处理
  6. if (error.error == QJsonParseError::NoError) {
  7.     if (!(jsonDocument.isNull() || jsonDocument.isEmpty())) {
  8.         if (jsonDocument.isObject()) {
  9.             // ...
  10.         } else if (jsonDocument.isArray()) {
  11.             // ...
  12.         }
  13.     }
  14. } else {
  15.     // 检查错误类型
  16. }
QVariant对象生成 JSON 文档也很简单:

点击(此处)折叠或打开

  1. QVariantList people;

  2. QVariantMap bob;
  3. bob.insert("Name", "Bob");
  4. bob.insert("Phonenumber", 123);

  5. QVariantMap alice;
  6. alice.insert("Name", "Alice");
  7. alice.insert("Phonenumber", 321);

  8. people << bob << alice;

  9. QJsonDocument jsonDocument = QJsonDocument::fromVariant(people);
  10. if (!jsonDocument.isNull()) {
  11.     qDebug() << jsonDocument.toJson();
  12. }



阅读(1360) | 评论(0) | 转发(0) |
0

上一篇:QThread简单示例

下一篇:Qt数据库操作

给主人留下些什么吧!~~