在 Qt 4.7 中解析 JSON 的最简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4169988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
easiest way to parse JSON in Qt 4.7
提问by wael34218
I need to parse JSON object through Qt. What is the easiest/fastest way to do it?
我需要通过 Qt 解析 JSON 对象。最简单/最快的方法是什么?
采纳答案by Etienne Savard
Try QJson.
试试QJson。
QJson is actively developed (and used by KDE, if I'm not mistaken). The best is to checkout the source code directly and built it yourself. There is no dependencies to QJson (except for Qt and CMake). It's pretty simple to use too, have a look at some usage examples :
QJson 正在积极开发(如果我没记错的话,被 KDE 使用)。最好是直接签出源代码,自己构建。没有对 QJson 的依赖(Qt 和 CMake 除外)。使用起来也很简单,看看一些使用示例:
回答by laurent
JSON parsing is now supported in Qt 5. Here's how to load and parse a document:
Qt 5 现在支持 JSON 解析。以下是加载和解析文档的方法:
#include <QByteArray>
#include <QFile>
#include <QJsonObject>
#include <QJsonDocument>
// ...
// Read JSON file
QFile file("/path/to/file.json");
file.open(QIODevice::ReadOnly);
QByteArray rawData = file.readAll();
// Parse document
QJsonDocument doc(QJsonDocument::fromJson(rawData));
// Get JSON object
QJsonObject json = doc.object();
// Access properties
qDebug() << json["something"].toString();
回答by guruz
If you don't want to depend on external libraries you could use the QScriptEngine
如果你不想依赖外部库,你可以使用 QScriptEngine
http://qtwiki.remdex.info/Parsing_JSON_with_QT_using_standard_QT_library
http://qtwiki.remdex.info/Parsing_JSON_with_QT_using_standard_QT_library
回答by user2243820
Here is Qt style json encoder/decoder
这是 Qt 风格的 json 编码器/解码器
#include "json.h"
#include <QScriptEngine>
#include <QScriptValueIterator>
Json::Json()
{
}
QString Json::encode(const QMap<QString,QVariant> &map)
{
QScriptEngine engine;
engine.evaluate("function toString() { return JSON.stringify(this) }");
QScriptValue toString = engine.globalObject().property("toString");
QScriptValue obj = encodeInner(map, &engine);
return toString.call(obj).toString();
}
QMap<QString, QVariant> Json::decode(const QString &jsonStr)
{
QScriptValue object;
QScriptEngine engine;
object = engine.evaluate("(" + jsonStr + ")");
return decodeInner(object);
}
QScriptValue Json::encodeInner(const QMap<QString,QVariant> &map, QScriptEngine* engine)
{
QScriptValue obj = engine->newObject();
QMapIterator<QString, QVariant> i(map);
while (i.hasNext()) {
i.next();
if (i.value().type() == QVariant::String)
obj.setProperty(i.key(), i.value().toString());
else if (i.value().type() == QVariant::Int)
obj.setProperty(i.key(), i.value().toInt());
else if (i.value().type() == QVariant::Double)
obj.setProperty(i.key(), i.value().toDouble());
else if (i.value().type() == QVariant::List)
obj.setProperty(i.key(), qScriptValueFromSequence(engine, i.value().toList()));
else if (i.value().type() == QVariant::Map)
obj.setProperty(i.key(), encodeInner(i.value().toMap(), engine));
}
return obj;
}
QMap<QString, QVariant> Json::decodeInner(QScriptValue object)
{
QMap<QString, QVariant> map;
QScriptValueIterator it(object);
while (it.hasNext()) {
it.next();
if (it.value().isArray())
map.insert(it.name(),QVariant(decodeInnerToList(it.value())));
else if (it.value().isNumber())
map.insert(it.name(),QVariant(it.value().toNumber()));
else if (it.value().isString())
map.insert(it.name(),QVariant(it.value().toString()));
else if (it.value().isNull())
map.insert(it.name(),QVariant());
else if(it.value().isObject())
map.insert(it.name(),QVariant(decodeInner(it.value())));
}
return map;
}
QList<QVariant> Json::decodeInnerToList(QScriptValue arrayValue)
{
QList<QVariant> list;
QScriptValueIterator it(arrayValue);
while (it.hasNext()) {
it.next();
if (it.name() == "length")
continue;
if (it.value().isArray())
list.append(QVariant(decodeInnerToList(it.value())));
else if (it.value().isNumber())
list.append(QVariant(it.value().toNumber()));
else if (it.value().isString())
list.append(QVariant(it.value().toString()));
else if (it.value().isNull())
list.append(QVariant());
else if(it.value().isObject())
list.append(QVariant(decodeInner(it.value())));
}
return list;
}
回答by Evan Teran
I know this answer is late, but I recently created a project to help create code which is meant to compile on both Qt4 and Qt5 and deals with JSON.
我知道这个答案来晚了,但我最近创建了一个项目来帮助创建旨在在 Qt4 和 Qt5 上编译并处理 JSON 的代码。
https://code.google.com/p/qjson4/
https://code.google.com/p/qjson4/
This library is indented to be a drop in replacement for QJsonDocumentin Qt4 and will use Qt's classes when used in Qt5. So it should be a fairly smooth transition. It's not 100% complete, but the major features are in there :-).
该库旨在替代QJsonDocumentQt4中的替代品,并且在 Qt5 中使用时将使用 Qt 的类。所以它应该是一个相当平稳的过渡。它不是 100% 完整,但主要功能都在那里:-)。
回答by AntonyG
I would recommend qjson-backport, as it uses the same API as in Qt5.
我会推荐qjson-backport,因为它使用与 Qt5 相同的 API。
You can conditionally load the library when you use Qt4, and use the default implementation when using Qt5.
使用Qt4时可以有条件地加载库,使用Qt5时使用默认实现。
My qjson.prifile looks like:
我的qjson.pri文件看起来像:
!greaterThan(QT_MAJOR_VERSION, 4): {
INCLUDEPATH += \
$$PWD
SOURCES += \
$$PWD/qjson.cpp \
$$PWD/qjsonarray.cpp \
$$PWD/qjsondocument.cpp \
$$PWD/qjsonobject.cpp \
$$PWD/qjsonparser.cpp \
$$PWD/qjsonvalue.cpp \
$$PWD/qjsonwriter.cpp
HEADERS += \
$$PWD/qjson_p.h \
$$PWD/qjsonarray.h \
$$PWD/qjsondocument.h \
$$PWD/qjsonobject.h \
$$PWD/qjsonparser_p.h \
$$PWD/qjsonvalue.h \
$$PWD/qjsonwriter_p.h
}

