我对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"]
        }
    ]
}

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

为此,我使用了String的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;

肯定有一个很好的方法来执行此操作,因为它不起作用,并且我没有找到任何有用的示例

最佳答案

使用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;
}

07-23 05:03