简体   繁体   中英

Cannot convert std::string to QJsonArray in Qt

The following text is a bit of std::string text that is generated by another app (I do not have control of what the app sends me). I have tried for days to get this converted into a QJsonArray and cannot figure this out. I am using C++ within QT. Does anyone have a bit of direction or sample C++ code that could solve this?

{
  "saved_mik_yous": {

    "2120ce2d-a5b1-49b8-8384-3781b7b2d73b": {
      "name": null,
      "id": "2120ce2d-a5b1-49b8-8384-3781b7b2d73b",
      "start": 1565288936.1127193,
      "end": 1565289128.1236603,
      "mixxer": 128.567505,
      "mik_source": "algo"
    },
    "bf855c0d-a71d-42ea-b3ef-7cbe0e2c7a3d": {
      "name": null,
      "id": "bf855c0d-a71d-42ea-b3ef-7cbe0e2c7a3d",
      "start": 1565301673.4609745,
      "end": 1565301832.665656,
      "mixxer": 308.485107,
      "mik_source": "algo"
    }
  },
  "mik_you_state": "completed"
}

All you have to do is this:

QJsonDocument doc = QJsonDocument::fromJson(QByteArray::fromStdString(str));

Then, you can access the values for the keys for example as:

doc["saved_mik_yous"]

And so on.

Mind you, the json you are showing seems to be an object rather than an array since it contains key-value pairs rather than a list of elements inside square brackets. So, whilst it does not matter when you are converting the std::string into a QJsonDocument, you need to access the values by keys rather than indices.

If you are getting dynamic json which can be either an array or object, you can always check for the type with isArray() or isObject() to convert it to the right type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM