我在qt5应用程序中从pusher.com WebSocket获取了一些json数据,我正在努力解析他们发送的“序列化”json。我终于确定了问题,但我不确定如何解决它:
我做了一个小测试程序来演示:
QString str1 = "{\"event\":\"message\",\"data\":\"{\\\"channel\\\":\\\"trade.3\\\",\\\"trade\\\":{\\\"tradeid\\\":\\\"86364698\\\",\\\"timestamp\\\":1425420405,\\\"datetime\\\":\\\"2015-03-03 17:06:45 EDT\\\",\\\"marketid\\\":\\\"3\\\",\\\"marketname\\\":\\\"LTC\\\\/BTC\\\",\\\"quantity\\\":\\\"0.24680554\\\",\\\"price\\\":\\\"0.00694988\\\",\\\"total\\\":\\\"0.00171527\\\",\\\"type\\\":\\\"Buy\\\"}}\",\"channel\":\"trade.3\"}";
QString str2="{\"event\":\"message\",\"data\": {\"channel\":\"trade.3\",\"trade\":{\"tradeid\":\"86364698\",\"timestamp\":1425420405,\"datetime\":\"2015-03-03 17:06:45 EDT\",\"marketid\":\"3\",\"marketname\":\"LTC\\/BTC\",\"quantity\":\"0.24680554\",\"price\":\"0.00694988\",\"total\":\"0.00171527\",\"type\":\"Buy\"}},\"channel\":\"trade.3\"}";
QJsonDocument doc1 = QJsonDocument::fromJson(str1.toUtf8());
QJsonDocument doc2 = QJsonDocument::fromJson(str2.toUtf8());
qDebug("%s", qPrintable(QString("Str1: \"%1\"").arg(str1)));
qDebug("%s", qPrintable(QString(doc1.toJson())));
qDebug() << "-----------------------------------------------------------";
qDebug("%s", qPrintable(QString("Str2: \"%1\"").arg(str2)));
qDebug("%s", qPrintable(QString(doc2.toJson())));
输出:
Str1: "{"event":"message","data":"{\"channel\":\"trade.3\",\"trade\":{\"tradeid\":\"86364698\",\"timestamp\":1425420405,\"datetime\":\"2015-03-03 17:06:45 EDT\",\"marketid\":\"3\",\"marketname\":\"LTC\\/BTC\",\"quantity\":\"0.24680554\",\"price\":\"0.00694988\",\"total\":\"0.00171527\",\"type\":\"Buy\"}}","channel":"trade.3"}"
{
"channel": "trade.3",
"data": "{\"channel\":\"trade.3\",\"trade\":{\"tradeid\":\"86364698\",\"timestamp\":1425420405,\"datetime\":\"2015-03-03 17:06:45 EDT\",\"marketid\":\"3\",\"marketname\":\"LTC\\/BTC\",\"quantity\":\"0.24680554\",\"price\":\"0.00694988\",\"total\":\"0.00171527\",\"type\":\"Buy\"}}",
"event": "message"
}
-----------------------------------------------------------
Str2: "{"event":"message","data": {"channel":"trade.3","trade": {"tradeid":"86364698","timestamp":1425420405,"datetime":"2015-03-03 17:06:45 EDT","marketid":"3","marketname":"LTC\/BTC","quantity":"0.24680554","price":"0.00694988","total":"0.00171527","type":"Buy"}},"channel":"trade.3"}"
{
"channel": "trade.3",
"data": {
"channel": "trade.3",
"trade": {
"datetime": "2015-03-03 17:06:45 EDT",
"marketid": "3",
"marketname": "LTC/BTC",
"price": "0.00694988",
"quantity": "0.24680554",
"timestamp": 1425420405,
"total": "0.00171527",
"tradeid": "86364698",
"type": "Buy"
}
},
"event": "message"
}
显然第二个版本是我的目标。有没有办法轻松转换输入数据,或者我将不得不尝试滚动我自己的转换器功能?
编辑:以下是关于这个特定数据样本的技巧......但我仍然认为必须有更合适的方法来转换这种东西......
str1.replace("\\\"", "\"");
str1.replace("\\\\", "\\");
str1.replace("\"{", "{");
str1.replace("}\"", "}");
答案 0 :(得分:0)
您的&#34;数据&#34;实际上是另一个JSON文档。
只需从doc1.object()创建另一个QJsonDocument [&#34;数据&#34;]。toString();
但它明确表示&#34;数据&#34;可以有其他东西,在这个例子中它是一个json doc。
祝你好运!