如何从QString初始化QJsonObject

时间:2014-11-07 15:34:25

标签: c++ json qt

我对Qt很新,我想做一个非常简单的操作: 我必须获得以下JSonObject:

{
    "Record1" : "830957 ",
    "Properties" :
    [{
            "Corporate ID" : "3859043 ",
            "Name" : "John Doe ",
            "Function" : "Power Speaker ",
            "Bonus Points" : ["10 ", "45", "56 ", "34", "56", "10 ", "45", "56 ", "34", "56", "10 ", "45", "56 ", "34", "56", "10 ", "45", "56 ", "34", "56", "10 ", "45", "56 ", "34", "56 ", "10", "45 ", "56", "34 ", "56", "45"]
        }
    ]
}

使用此语法和有效性检查器检查了JSon:http://jsonformatter.curiousconcept.com/并且发现它有效。

我为此使用了字符串的QJsonValue初始化并将其转换为QJSonObject:

QJsonObject ObjectFromString(const QString& in)
{
    QJsonValue val(in);
    return val.toObject();
}

我正在加载从文件中粘贴的JSon:

QString path = "C:/Temp";
QFile *file = new QFile(path + "/" + "Input.txt");
file->open(QIODevice::ReadOnly | QFile::Text);
QTextStream in(file);
QString text = in.readAll();
file->close();

qDebug() << text;
QJsonObject obj = ObjectFromString(text);
qDebug() <<obj;

这肯定是一个很好的方法,因为这不起作用,我没有找到任何有用的例子

2 个答案:

答案 0 :(得分:27)

使用QJsonDocument::fromJson

QString data; // assume this holds the json string

QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8());

如果你想要QJsonObject ...

QJsonObject ObjectFromString(const QString& in)
{
    QJsonObject obj;

    QJsonDocument doc = QJsonDocument::fromJson(in.toUtf8());

    // check validity of the document
    if(!doc.isNull())
    {
        if(doc.isObject())
        {
            obj = doc.object();        
        }
        else
        {
            qDebug() << "Document is not an object" << endl;
        }
    }
    else
    {
        qDebug() << "Invalid JSON...\n" << in << endl;
    }

    return obj;
}

答案 1 :(得分:0)

您必须执行此步骤

  1. 首先将Qstring转换为QByteArray
  2. 将QByteArray转换为QJsonDocument
  3. 将QJsonDocument转换为QJsonObject
QString str = "{\"name\" : \"John\" }";

QByteArray br = str.toUtf8();

QJsonDocument doc = QJsonDocument::fromJson(br);

QJsonObject obj = doc.object();

QString name = obj["name"].toString();
qDebug() << name;