QByteArray in Json

How to convert a QByteArray from a JSON response network?

Check with the function below:

void GridSample::requestFinished( QNetworkReply * reply){
    QVariantMap dataName;
            if (reply) {
                if (reply->error() == QNetworkReply::NoError) {
                    const int available = reply->bytesAvailable();
                    if (available > 0) {
                        const QByteArray buffer(reply->readAll());

                        bb::data::JsonDataAccess ja;
                        const QVariant jsonva = ja.loadFromBuffer(buffer);
                        const QVariantMap jsonreply = jsonva.toMap();
                        QVariantList data = jsonreply["photos"].toList();
                        foreach(QVariant v, data){
                            dataName["text"]=v.toMap().value("created_at").toString();
                            myGroupModel->insert(dataName);
                        }
                    }
                } else {

                }
                reply->deleteLater();
            }
}

Tags: BlackBerry Developers

Similar Questions

  • Qbytearray json analytical problems

    help the analysis of this json:

    {"coord":{"lon":-97.87,"lat":22.26},"sys":{"country":"MX","sunrise":1383827966,"sunset":1383868260},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"cmc stations","main":{"temp":26.928,"temp_min":26.928,"temp_max":26.928,"pressure":1026.4,"sea_level":1027.46,"grnd_level":1026.4,"humidity":85},"wind":{"speed":4.46,"deg":77.0002},"clouds":{"all":0},"dt":1383786373,"id":3530594,"name":"Ciudad Madero","cod":200}
    

    I got it in a QByteArray as a buffer but I do not know how to mapping to take every part of it and use it on my labels later, I got this far and got some of them, but just a label

    const QByteArray buffer (response-> readAll());
    bool ok;

    BB::data :: JsonDataAccess ja;
    const QVariant jsonva = ja.loadFromBuffer (buffer);
    const QMap externalip = jsonva.toMap ();

    foreach (const QVariant & value, externalip) {}
    response += Celsius.ToString;
    }

    Consider the country...

    In the header, you would have a property:

    public:
    Q_PROPERTY (QString country READ country WRITE setCountry NOTIFY countryChanged);
    Q_INVOKABLE QString country() {
    return _country;
    }
    Q_SLOT void setCountry(QString c) {
      if (c!=_country) {
        _country = c;
        emity countryChanged(c);
      }
    }
    
    signals:
      void countryChanged(QString);
    
    private:  QString _country
    

    TheBody - that you had received new JSON

        JsonDataAccess jad;
        QVariantMap map(jad.loadFromBuffer(fred).toMap());
        QVariantMap sys(map["sys"].toMap());
        setCountry(sys["country"].toString());
    

    The QML would need to be linked to the property in the countryside...

  • How to create a Json structure programmatically in Qt

    Hi all

    I know to parse a json structure, but not vice versa.

    This is the structure that I need to create.

    {'3': ['Num accounts', '1'], '2': ['Version', '1'], '1': ["OS, BB10", '10.2.1.0'], '4': ['Local', 'en_US']}

    Can someone tell me how do in a standard way.

    Look here

    https://developer.BlackBerry.com/native/reference/Cascades/bb__data__jsondataaccess.html#function-SA...

    QByteArray buffer;
    JsonDataAccess jda;
    jda.saveToBuffer(QVariant(map), &buffer);qDebug() << buffer;
    
  • JSON format - Date and special characters

    Hi all

    I had a JSON server in which, I have a few text values and date.

    1. How can I convert special characters to normal String.e.g. Comma etc. ?
    2. How can I convert long date, a string in the format e.g. "1345670466960-0400"?

    I really appreciate any help above.

    Solved... Where the above closure. For others, I will post the solution.

    Special characters-

    QByteArray buffer(bufSize, 0);
    int read = reply->read(buffer.data(), available);
    //response = QString(buffer); -- Wrong way to convert the bytes.
    response = QString::fromUtf8(buffer); // right way, so special character handled itself.
    

    Day fromatting - for example "/ Date (1345670466960-0400).

    QString getStringDate(QString k){
        QDateTime date = QDateTime::fromTime_t(getDate(k));
        QString strDate = date.toString("MM/dd/yyyy HH:mm:ss");
        return strDate;
    }
    long getDate(QString k) {
        long rc = 0;
        QString v = k;
        if (v.length() > 0 ) {
            int b = v.indexOf("/Date(");
            if (b >= 0) {
                b += 6;
                int e = v.indexOf(')', b);
                if (e > b) {
                    QString s = v.mid(b, e);
                    int sign = 1;
                    if (s.indexOf('-') > 0 || s.indexOf('+') > 0) {
                        sign = s.indexOf('-') > 0 ? -1 : 1;
                        e = sign < 0 ? s.indexOf('-') : s.indexOf('+');
                        s = s.mid(0, e);
                    }
                    bool *ok = false;
                    s = s.mid(0, s.length() - 3); //trimming it for seconds only....
                    rc = s.toLong(ok, 0);
                }
            }
        }
        return rc;
    }
    
  • QNetworkReply running into the problem of loading JSON data

    Hello

    I am a beginner with C++ and QT, but so far I'm starting to love the NDK waterfall!

    I'm trying to load a json data file that is extracted via a http request. Everything goes through, but my json data simply would not load in the QVariantList. So after a few hours of poking arround, I noticed finally that the json returned by the http request data is missing two brackets [] (an @ beginning and an end @).

    When I load the json data into a file with the two brakets included, the QVariantList load properly and I can debug through the records...

    Now my question is... how C++ can I add those parentheses []... See the code example below:

    void MyJSONReadClass::httpFinished()
    {
      JsonDataAccess jda;
      QVariantList myDataList;
    
      if (mReply->error() == QNetworkReply::NoError)
      {
        // Load the data using the reply QIODevice.
        qDebug() << mReply;
        myDataList = jda.load(mReply).value();
      }
      else
      {
        // Handle error
      }
    
      if (jda.hasError())
      {
        bb::data::DataAccessError error = jda.error();
        qDebug() << "JSON loading error: " << error.errorType() << ": "
            << error.errorMessage();
        return;
      }
    
      loadData(myDataList);
    
      // The reply is not needed now so we call deleteLater() function since we are in a slot.
      mReply->deleteLater();
    }
    

    Also, I would have thought that the jda.hasError () have captured this question... but guess not!

    I use the wrong approach or wrong classes? The basic example used is the WeatherGuesser project.

    Thanks for your help...

    It is perhaps not related to media. Try to recover data from QNetworkResponse as a QByteArray then load it into JsonDataAccess using loadFromBuffer:

     myDataList = jda.loadFromBuffer(mReply.readAll()).value();
    

    If this is insufficient, you can add media in this way (not tested, please see the documentation for the names of functioning if it won't compile):

    QByteArray a = mReply.readAll();
    a.insert(0, '[');
    a.append(']');
    myDataList = jda.loadFromBuffer(a).value();
    

    Note that if the response data are zero end (most likely it is not, but there is a possibility of it), you will need to check if the last symbol in byte array is '\0' and insert the capture media.

    QByteArray docs:

    http://Qt-project.org/doc/Qt-4.8/QByteArray.html

  • How to replace the string "\" on json webservice?

    Hello

    I have problem with this json

    "{\"search_result\":[{\"name\":\"Mall Summarecon\",\"category\":\"BusinessEntity\",\"id\":\"1\"},{\"name\":\"Bamboo Dim Sum\",\"category\":\"BusinessEntity\",\"id\":\"2\"},{\"name\":\"Dimsum Ceker\",\"category\":\"Item\",\"id\":\"1\"}]}"
    

    I want to replace the string "\".

    the json are already working on my app via .cpp file

    I already add json.replace on my qml

    function simpleSearch(response){
            indicator.stop()
            model.clear()
            console.log("Response: "+response)
            var json = JSON.parse(response)
            json = json.replace('\\', ' ') // this is how the way i replace
            if (json == "[]")
                notFound.visible = true
    
            else
                model.append(json.search_result)
        }
    

    but still does not work

    is there a different way to replace it?

    Thank you

    Change your simpleSearchFinished as follows

    ....simpleSearchFinished()
    {
        QNetworkReply *reply = qobject_cast(sender());
        if (!reply->error()){
            QByteArray response = reply->readAll();
            response.replace("\\", "");
            if (response.startsWith("\"")){
                response.remove(0, 1);
            }
            if (response.endsWith("\"")){
                response.remove(response.length()-1, 1);
            }
            emit simpleSearchDone(response);
        }else{
            const int httpCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
            qDebug() << "ErrorCode" << httpCode << endl << \
                    "ErrorString" << reply->errorString();
            emit error(httpCode, reply->errorString());
        }
        reply->deleteLater();
        manager->deleteLater();
    }
    

    and QML

    function simpleSearch(response){
        indicator.stop()
        model.clear()
        var json = JSON.parse(response)
        if (json){ // is VALID/PARSED
            model.append(json.search_result)
        }
    }
    

    As I wrote, it is not a good workaround solution. The best is to send VALID JSON string directly from your server. But it works

  • Reading of the key / value to Json in Blackberry 10

    Hi all

    My BB 10 App connects to a TCP socket and reads the JSON data as this format
    {'Symbol': "SMB1": 88.455479126222713 "AskPrice": 78.556789999999992, "BidPrice": 78.35679, "open": 78.45679, "top"}
    {'Symbol': 'SMB2', "AskPrice": 45.672380000000004, "BidPrice": 45.47238, "open": 45.57238, "top":55.566967544349296}...}

    Display each data as a separate list of point symbols. IE SMB1 in a list and SMB2 element in another element in the list and so on.

    now my Questions are:

    1-question: when I try to show above Listview data in JSON Format is Empty.Does 'JsonDataAccess' accept above Json format? but when I add before (with "[" "]"), after adding
    (with "]") ") and separated by a","at the very top of the JSON format. I can learn Listview.
    That is to say
    [{"Symbol": "SMB1", "AskPrice": 78.82, "BidPrice": 78.23,: 78.30 'Open', 'High': 78.80: 78.31 'Low', 'close': 78.18}, {...}, {...}] Is there any alternation with attach them like that?

    Question-2: [{"Symbol": "SMB1", "AskPrice": 78.82, "BidPrice": 78.23,: 78.30 'Open', 'High': 78.80: 78.31 'Low', 'close': 78.18}, {...}, {...}]
    How to access the key pairs / value of this JSON?

    my code is like:

    JDA JsonDataAccess;
    QVariant jda.loadFromBuffer (jsonData) = qtData;
    Here's jsonData, QByteArray and contains the above Json data.

    and model for the display of the list, it's like
    GroupDataModel * model = new GroupDataModel (QStringList ());
    model-> setParent (this);
    model-> insertList (()) qtData.value;
    model-> setGrouping (ItemGrouping::None);
    model-> setDataModel ();
    Question - 3:
    How to update a specific list item in the ListView so Json is like
    [{"Symbol": "SMB-1", "Askprice": 100...},]
    [{"Symbol": "SMB-1", "Askprice": 200...}]. Same symbol as 'SMB-1' is repeated, I want to update this particular list item, but not to add it as another element of the list.

    Thanks in advance... Hope has a solution here...

    Welcome to the forum

    to make your code more readable please use 'Insert Code' of the RichText Editor

  • Maps JSON data with two data in the list

    Hey all,.

    Been working with JSON data and informing the lists for a some time now, but im stuck now on a single set of data.

    The data structure is the following:

    [
         {
              data: {
                   children: [ {
                        {}
                        {}
                        {}
                   } ]
               }
         }
    
         {
              data: {
                   children: [ {
                        {}
                        {}
                        {}
                   } ]
               }
         }
    ]
    

    The data that I take care of normally contains one of these structures and not 2 as in the above data. So what follows could could work:

                                    const QByteArray response(reply->readAll());
            ArrayDataModel *model = new ArrayDataModel();
    
            bb::data::JsonDataAccess jda;
            QVariantMap results = jda.loadFromBuffer(response).toMap();
            QVariantList children = results["data"].toMap()["children"].toList();
    
            model->append(children);
            mListView->setDataModel(model);
    

    However, it is now giving me an empty list. So how can I limit the above code to analyze and insert only the 2nd set of JSON data in the list?

    Please let me know if it needs to be clarified. Any help is appreciated. Thank you!

    Hello

    It contains a list of maps. Have you tried something like the following:

    bb::data::JsonDataAccess jda;
    QVariantList results = jda.loadFromBuffer(response).toList();if (results.size() >= 2){
        QVariantMap secondSet = results.at(1).toMap(); // to get the second map
        QVariantList children = secondSet["data"].toMap()["children"].toList();
        model->append(children);}
    
  • Help with JSON HTTP Post request

    Still fairly new to QT so I try to send a query with some json http post, I'm pulling the json to a file and which seems to work fine but I get a http 500 error. I want to just make sure that my code is correct before contacting the company that webservice I use here is my code:

     JsonDataAccess jda;
        QVariant list = jda.load(QDir::currentPath() +"/app/native/assets/jsonData/myjson.json");
    
        qDebug()<post(request, list.toByteArray());
    

    I have a feeling that I'm passing in json data in the wrong post method. Any help is appreicated

    Hello

    You send an empty server string because list.toByteArray () returns an empty string.

    You must save the QByteArray list;

    QByteArray result;
    jda.saveToBuffer(list, &result);
    
    // and then
    
    QNetworkReply *reply = networkAccessManager->post(request, result);
    

    or

    Simply load the json with QFile file

    QFile file(YOUR_JSON);
    if (!file.open(QIODevice::ReadOnly)){
        qDebug() << Q_FUNC_INFO << file.errorString();
        return;
    }
    QByteArray result = file.readAll();
    file.close()
    
    QNetworkReply *reply = networkAccessManager->post(request, result);
    

    Hoe it helps

  • I want to move the bookmarks to a no start Win disk (format jspn) to win 10 PC. The import dialog box wants html, not json format

    the motherboard on my old PC to WIn 7 has become damaged. I took the hard e drive: toward a new win 10 PC. I can find the Archives of bookmark on the old disk - files are in json format, but when I try to import the bookmarks file I can only find a way to import them into html format. How do I resolve this condition glare?

    If the file is in json format, then it replaces the current file.

    To open the bookmark, Manager press the ALT or F10 to rise
    the tool, then select bookmarks.
    Access key is < Control >(Mac = < Command >) < shift > B.

    Once the window is open, the top of the page, press the button
    Import and backup. Select export bookmarks to HTML and follow
    prompts and save it in a HTML file. Copy the file to another computer.
    Repeat the above instructions, BUT select Import Bookmarks in HTML,

    JSON files. Do as above, but select restore. The file must be in the
    Bookmarks backup folder.

  • All IT gurus out there who know Firefox... have lost the passwords saved when FF created a new profile and delete old files key3.dbf and logins.json profile.

    All IT gurus out there who know Firefox... have lost the passwords saved when FF created a new profile and delete old files key3.dbf and logins.json profile. Any ideas, anyone?

    So it's not a logins.json file?

    I see a signons3.txt file and a file signons.sqlite older, if you can try to see if you can import passwords stored in this file.

    You can force Firefox to re-import the passwords in the file signons.sqlite and regenerate the file logins.json with the following steps:

    • reset the signon.importedFromSqlite pref on the topic: config page by default via the context menu
    • Delete the logins.json file in the closed Firefox with Firefox profile folder

    When you restart Firefox, then you should have the pref signon.importedFromSqlite with the value set to true.
    You have passwords that are imported in the password manager, unless there were errors or signons.sqlite signons3.txt.

    You can open the topic: config page via the address bar.
    You can accept the warning and click on "I'll be careful" to continue.

    You can use this button to go to the current Firefox profile folder:

  • Is it possible to recover the logins.json.corrupt?

    Yesterday, I lost all my passwords after a bizarre episode (see https://support.mozilla.org/en-US/questions/1085073 and https://support.mozilla.org/en-US/questions/1085300 ). I have a file logins.json in the folder of my profile with any passwords, I was able to rebuild, and in the same folder is logins.json.corrupt (27K, 24740 characters according to the Texpad, but none of them visible - blank page). This response (https://support.mozilla.org/en-US/questions/1054932 ) - reset signon.importedFromSqlite, close FF, delete logins.json and re - open - did not work. But I have re-set 'value (user)' in signon.importedFromSqlite - maybe I should reset 'value '?

    Just checked - reset the value did not help either.

    COR - el said

    You can check if there are previous versions of the files logins.json and key3db.

    • Right click: properties > Previous Versions

    There is no way of knowing if you have a correct signons3.txt file.
    If it works, then you see the names in the password manager.
    Otherwise, you will see an error message or a blank password Manager window.

    Yes! Thank you 1 million. Get all of my passwords.

    For those who have found this answer: I opened my profiles, right-click on logins.json file, having consulted the "Previous Versions" property page He produced a list of three. In the list, right click on one of the last week, the option is useful that was 'copy '. Copied and pasted on the desktop, where logins.json recovered appeared. Then copied logins.json current profiles Safe Placez_ the (fair value), and then deleted the Profiles folder and replaced with the recovered version.

  • I'm trying to import and backup/restore/Choose file... / after backup correctly and I see the file, but there is no JSON extension. What can I do?

    I'm trying to import and backup/restore/Choose file... / after backup correctly and I see the file, but there is no JSON extension. What can I do?

    I backed up my favorites using 'import and backup/Backup' on an external HD, installed Windows 10 and went to restore my bookmarks and noticed the file named "Firefox bookmarks-2015-09-04"had no extension and does not work."

    Please advise! Thank you! Sincerely, s

    If you add the .json extension, it works then? Why people who design browsers or extensions them do create files with no extension name, in spite that these extension names are essential to make the files can be restored? I could never understand that.

  • Does not start, need more and more memory, then crashes. It is SOLVED by deleting DB, panacea.dat, foldertree.json CAUSE global messages: uknown

    As a user of Thunderbird long term (currently version 38.2.0 on Win7 x 86 US) today, I caught myself (negatively) by the following problem: at the launch at the start of Thunderbird, the window will appear last closed (and for a short while, I see my files, etc., as left behind, during the last closure of Thunderbird), but then it turns into State "Not responding" (nothing works). When we look in the Task Manager, I see that Thunderbird seizes more and more memory, before this date - after a few seconds - crashing. I really hope that for some help fast, if possible (I desperately need a solution for e-mail job well - ideally the one I had, i.e. Thunderbird with my settings).

    What I tried:
    -Uninstall Thunderbird and install it again (did not help)
    -Uninstall Thunderbird and install an older version (I tried 38.1.0, 38.0.2, and 31.8.0 - nothing has worked)
    -from Thunderbird in SafeMode (same problem)
    -from Thunderbird in safe mode of Windows (same problem)
    -from Thunderbird in offline mode (did not help)

    My main question to know how to solve this problem, includes questions such as
    ? Should I try to delete some files of Thunderbird and try again (which ones?)?
    ? Can I use a command line "tricks" to get Thunderbird started?
    Etc.

    Thanks for your help!

    I think I solved my problem: delete messages from global reach DB and panacea.dat foldertree.json helped - once Thunderbird started again interactively and now I can restore my data files/messages.

  • Is there a way to convert the compressed files jsonlz4 in json?

    Hi, is it possible to learn how to properly restore a session of bookmarks via the jsonlz4 file? Firefox lost all my favorites, and when you try to restore using the recovery with the latest jsonlz4 file session the process simply does not end, starts but after a few hours, is still running, with warnings of continuos scripts held or stopped responding. Is it possible to do this correctly? Or a tool to convert the jsonlz4 compressed into json, perhaps html.
    Thank you.

    Well gentlemen: I definitely gave up; whatever the reason, the issue is not resolved. I stay with the old bookmark html, necessarily.
    Thanks for jscher and co - ADR efforts and goodbye.

Maybe you are looking for