usage-QJson

COME FROM : usage-QJson

 

Usage

This page provides a quick overview of QJson’s features:

  • parsing: from JSON to QVariant.
  • serializing: from QVariant to JSON.
  • QObject helper: dump and restore QObject’s attributes.

For more details checkout QJson’s documentation.

 

Parsing: from JSON to QVariant

Converting JSON’s data to QVariant instance is really simple:

// create a Parser instance
QJson::Parser parser;

bool ok;

// json is a QString containing the data to convert
QVariant result = parser.parse (json, &ok);

Suppose you’re going to convert this JSON data:

{
  "encoding" : "UTF-8",
  "plug-ins" : [
      "python",
      "c++",
      "ruby"
      ],
  "indent" : { "length" : 3, "use_space" : true }
}

The following code would convert the JSON data and parse it:

QJson::Parser parser;
bool ok;

QVariantMap result = parser.parse (json, &ok).toMap();
if (!ok) {
  qFatal("An error occurred during parsing");
  exit (1);
}

qDebug() << "encoding:" << result["encoding"].toString();
qDebug() << "plugins:";

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

QVariantMap nestedMap = result["indent"].toMap();
qDebug() << "length:" << nestedMap["length"].toInt();
qDebug() << "use_space:" << nestedMap["use_space"].toBool();

The output would be:

encoding: "UTF-8"
plugins:
  - "python"
  - "c++"
  - "ruby"
length: 3
use_space: true

 


 

Serialization: from QVariant to JSON

QVariant objects are converted to a string containing the JSON data.

Let’s declare a QVariant object with some data to convert:

QVariantList people;

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

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

people << bob << alice;

Now it’s time to create the Serializer:

QJson::Serializer serializer;
bool ok;
QByteArray json = serializer.serialize(people, &ok);

if (ok) {
  qDebug() << json;
} else {
  qCritical() << "Something went wrong:" << serializer.errorMessage();
}

The output will be:

[ 
    { 
        "Name" : "Bob", "Phonenumber" : 123
    },
    { 
        "Name" : "Alice", "Phonenumber" : 321 
    } 
]

It’s possible to tune the indentation level of the resulting string using the Serializer::setIndentMode() method

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值