PHP解析JSON数组输出

时间:2015-01-02 02:20:34

标签: c++ arrays json qt

我有一个PHP返回的JSON数组,PHP的示例输出:

[
  {
    "uid": "1",
    "username": "mike",
    "time_created": "2014-12-27 15:30:03",
    "time_updated": "2014-12-27 15:30:03",
    "time_expires": "2014-12-27 15:30:03"
  },
  {
    "uid": "2",
    "username": "jason",
    "time_created": "2014-12-27 15:31:41",
    "time_updated": "2014-12-27 15:31:41",
    "time_expires": "2014-12-27 15:31:41"
  },
  {
    "uid": "3",
    "username": "david",
    "time_created": "2014-12-27 18:10:53",
    "time_updated": "2014-12-27 18:10:53",
    "time_expires": "2014-12-27 18:10:53"
  }
]

我尝试了几种方法,我尝试了Iterator,我尝试从JSonObject中获取,但似乎没有任何工作! 到目前为止,我有这个示例代码:

QJsonDocument jsonResponse = QJsonDocument::fromJson(JData.toUtf8());
QJsonObject jsonObject = jsonResponse.object();
for (QJsonObject:: Iterator it = jsonObject.begin(); it != jsonObject.end(); ++it) {
QJsonArray array= (*it).toArray();
foreach (const QJsonValue & v, array)
qDebug() << v.toString();

我尝试了其他几种方法,没有运气。我需要遍历这个JSON数据。请指教。我使用的是QT 5.4,C ++。

1 个答案:

答案 0 :(得分:1)

首先通过将数据放到QString来验证您的代码(并不意味着它需要完成,仅用于我的调试)。发现了几个问题:

  1. 数组位于文档的上一层。
  2. QJsonValue :: toString()无法遍历嵌套结构但是QJsonValue (变量v)仍然可以通过qDebug()流打印。

  3. QString JsonStr =
    "["
      "{"
        "\"uid\": \"1\","
        "\"username\": \"mike\","
        "\"time_created\": \"2014-12-27 15:30:03\","
        "\"time_updated\": \"2014-12-27 15:30:03\","
        "\"time_expires\": \"2014-12-27 15:30:03\""
      "},"
      "{"
        "\"uid\": \"2\","
        "\"username\": \"jason\","
        "\"time_created\": \"2014-12-27 15:31:41\","
        "\"time_updated\": \"2014-12-27 15:31:41\","
        "\"time_expires\": \"2014-12-27 15:31:41\""
      "},"
      "{"
        "\"uid\": \"3\","
        "\"username\": \"david\","
        "\"time_created\": \"2014-12-27 18:10:53\","
        "\"time_updated\": \"2014-12-27 18:10:53\","
        "\"time_expires\": \"2014-12-27 18:10:53\""
      "}"
    "]";
    
    QJsonDocument jsonResponse = QJsonDocument::fromJson(JsonStr.toUtf8());
    QJsonArray array = jsonResponse.array();
    // print
    foreach (const QJsonValue & v, array)
    {
        qDebug() << v;
    }
    
    // or parse
    foreach (const QJsonValue& v, array)
    {
        QJsonObject o = v.toObject();
        qDebug() << o["username"];
        qDebug() << o["time_expires"];
    }