Friday, June 14, 2013

Json parsing in BB 10

Generally, in many development technologies, we will be adding JSON api to project or provided by OS itself and parse the appropriate response using JSON API's. Here it is a different approach.
  1. Convert JSON response to QVariant using JsonDataAccess.
  2. Query the QVariant object for JSON children Nodes.
[
  {
    "id": "13",
    "en_description": "If leadership does not keep",
    "ar_description": "\u0625\u0646 \u0627",
    "date": "2012-09-28"
  },
  {
    "id": "14",
    "en_description": "The role of the leadership",
    "ar_description": "\u062f\u0648\u0631 \u0627",
    "date": "2012-09-28"
  }
]

In the above Json, I am likely to parse the data of "en_descreption" tag. The method to parse is shown below.

void Quotes::onUrlLoad(QString jsonResponse) {

    ArrayDataModel *arrayDataModel = new ArrayDataModel();

    //  Convert Json file into QTList objects.
    bb::data::JsonDataAccess ja;
    const QVariant jsonva = ja.loadFromBuffer(jsonResponse);
    const QList externalip = jsonva.toList();

    //  Iterate Json List and retrieve data, store it in ArraydataModel
    for (int index = 0; index < externalip.size(); index++) {

        QVariantMap map = externalip.at(index).toMap();
        QVariantMap::Iterator iterator = map.begin();
        while (iterator != map.end()) {
            //  Append "en_descreption" tag's value to the ArrayDataModel.
            if (!iterator.key().toStdString().compare("en_description")) {
                arrayDataModel->append(iterator.value().toString());
            }
            ++iterator;
        }   //  end while.
    }   //  end for

}

Above code does the following things 
  1. Loads Json string using JsonDataAcces.
  2. Converts the Json String to root QVariant object with the help of JsonDataAccess.
  3. Get the List of QVariant variables from the root QVariant variable . Note that as our JSON is an array hence we are using jsonva.toList(). Otherwise we have to use jsonva.toMap() as per documentation.
  4. Pull each QVariantMap from the list.
  5. Iterate the map for the values.
  6. Extract values with "en_description" and store it in ArrayDataModel.
That's it .. we are done with parsing and storing JSON data.

2 comments:

  1. Hi,

    can you Help me to solve this
    http://stackoverflow.com/questions/24306655/how-to-parse-object-in-the-soap-response-in-blackberry

    ReplyDelete
  2. thanks ... this did help me a lot (germany)

    ReplyDelete