JSON, QMap & QList

I tried to figure out how to insert correctly the data in a template to data using QList and QMap.

Here is the data that I was loaded from a Json file:

[
    {
        "firstName" : "Mike",
        "lastName" : "Chepesky",
        "contactInfo":[
            {
                "email":"[email protected]",
                "phone":"1-234-567-8910"
            }
        ],
        "employeeNumber" : 01840192
    },
    {
        "firstName" : "Westlee",
        "lastName" : "Barichak",
        "contactInfo":[
            {
                "email":"[email protected]",
                "phone":"1-234-567-8910"
            }
        ],
        "employeeNumber" : 47901927
    },
    {
        "firstName" : "Ian",
        "lastName" : "Dundas",
        "contactInfo":[
            {
                "email":"[email protected]",
                "phone":"1-234-567-8910"
            }
        ],
        "employeeNumber" : 29472012
    }
]

And I want to put all these data in a single hierarchy, then in a GroupDataModel. A bit like this:

[
    {
        "firstName" : "Mike",
        "lastName" : "Chepesky",
        "email":"[email protected]",
        "phone":"1-234-567-8910",
        "employeeNumber" : 01840192
    },
    {
        "firstName" : "Westlee",
        "lastName" : "Barichak",
        "email":"[email protected]",
        "phone":"1-234-567-8910",
        "employeeNumber" : 47901927
    },
    {
        "firstName" : "Ian",
        "lastName" : "Dundas",
        "email":"[email protected]",
        "phone":"1-234-567-8910",
        "employeeNumber" : 29472012
    }
]

so far, I have the following code which will get "firstName", "lastName" and "employeeNumber" in the GroupDataModel but I can't seem to figure out how to get 'email' and 'phone' in there.

    ListView *listView = root->findChild("qmlListView");

    GroupDataModel *model = new GroupDataModel(QStringList() << "firstName" << "lastName");    JsonDataAccess jda;

    QVariant jsonva = jda.load(QDir::currentPath() + "/app/native/assets/employees.json");

    QVariantList list = jsonva.toList();

    for (QList::iterator it = list.begin(); it != list.end(); it++)
    {
        QVariantMap map = it->toMap();
        model->insert(map);
    }

    listView->setDataModel(model);

Found a solution. The data hierarchy is preserved same key: value are set in QList and QMap. Therefor, all he need do is find the child table and throw it in a list. Once this is done you can retrieve the values from the list and unite those with the original map because it goes through an iterator. See the code below, and if anyone has any questions contact me.

    JsonDataAccess jda;

    //load JSON to a QVariant
    QVariant jsonva = jda.load(QDir::currentPath() + "/app/native/assets/employees.json");

    QVariantList list = jsonva.toList();

    for (QList::iterator it = list.begin(); it != list.end(); it++)
    {
        //Key-value pairs from list item put into a map
        QVariantMap map = it->toMap();

        //search key-value pairs for specific key of the array, in this case "contactInfo"
        QVariant childJsonva = map.value("contactInfo");

        //Take the key-value pairs from the variant above and put into QList
        QVariantList childList = childJsonva.toList();

        //iterate through the child list and put each key-value pair into a map
        for (QList::iterator childIt = childList.begin(); childIt != childList.end(); childIt++)
        {
            QVariantMap childMap = childIt->toMap();

            //combine child map with the original map
            map.unite(childMap);
        }

        model->insert(map);
    }

    // Set the data model for the list view
    listView->setDataModel(model);

Tags: BlackBerry Developers

Similar Questions

  • Display QList ListItemData &lt; QVariantMap &gt; with &lt; QVariantMap &gt; QListDataModel

    Hey,.

    I have a declared list like so:

    ListView {
                    id: PostsList
                    preferredWidth: 700
                    objectName: "PostsList"
                    layoutProperties: DockLayoutProperties {
                        horizontalAlignment: HorizontalAlignment.Center
                    }
    
                    // A single component because there's no list header.
                    listItemComponents: [
                        ListItemComponent {
                            type: "post"
                            PostItem {
                            }
                        }
                    ]
                                    //Tried this hoping items were being misparsed as headers.
                    function itemType(data, indexPath) {
                            return 'item';
                    }
                }
    

    Where is PostItem.qml

    Container {
        id: itemRoot
        layout: DockLayout {
            leftPadding: 30
            rightPadding: leftPadding
            topPadding: 30
        }
    
        Container {
            preferredHeight: 250
            layout: DockLayout {
            }
            Label {
                //text: ListItemData.data.title
                text: ListItemData.title
                layoutProperties: DockLayoutProperties {
                    verticalAlignment: VerticalAlignment.Center
                    horizontalAlignment: HorizontalAlignment.Center
                 }
            }        Label {            //text: ListItemData.data.title            text: ListItemData.description            layoutProperties: DockLayoutProperties {                verticalAlignment: VerticalAlignment.Center                horizontalAlignment: HorizontalAlignment.Center             }        } }
    
        // Signal handler for list item activation.
        ListItem.onActiveChanged: {
            setHighlight (ListItem.active);
        }
    
        // Signal handler for list item selection.
        ListItem.onSelectedChanged: {
            setHighlight (ListItem.selected);
        }
    }
    

    If you begin to feel that this code resembles stamp collector, you something...

    in any case, I stated as follows the data model for the list, copy the following code runs in a callback function SLOT QNetworkAccessManager...

    QList map;QVariantMap variant;foreach (post, posts)
    {
        variant.clear();
        variant.insert("id", post->id);
        variant.insert("title", post->title);
        variant.insert("author", post->author);
        map.insert(map.length(), variant);
    }
    
    ListView *PostsList = mNav->findChild("PostsList");
    
    QListDataModel *model = new QListDataModel;
    model->setParent(this);
    model->clear();
    
    QVariantMap v;
    int i = 0;
    foreach(v, map)
    {
        model->insert(i,v);
        i++;
    }
    
    PostsList->setDataModel(model);
    

    Here is what I expected to happen.

    I compile and debug the program. Some code I have send the network request. I analyze the JSON in a QList (which is my own type). From their I looked in a QList (map, called in the code above). Once I put my ListView data model as the variable according to the guidelines of this line:

    PostsList-> setDataModel (model);

    "PostsList" list updates in the application and displays the data from post-> title, as that inserted in the QVariant inserted in QVariantMap on this line:

    Variant. Insert ("title", post-> title);

    Instead, what is shown is the post-> data of the author, and the only reason I can possible design that is displayed (in reality the point post about 13 members, I removed most of length) is that it is the first in alphabetical order and seems to be the first member of the QVariantMap variable. The author of the message is the unique label presented, so declared both in the QML labels seem to be ignored.

    When I select a list item (by using the code is essentially identical to the example of stampcollector) and page through the QDeclarativeContext method all members of the QVariantMap are accessible and can be used to display items QML.

    Here is an example of how the stamp collector app that performs in the OnSelectionChanged handler:

    ListView* PostsList = dynamic_cast(sender());
    DataModel* Model = PostsList->dataModel();
    
    // Update the content view context property so that it corresponds to
    // the selected item and navigate to the page.
    QVariantMap map = Model->data(indexPath).toMap();
    mQmlContext->setContextProperty("_contentView", map);
    mNav->push(mContentPage);
    

    Can someone explain the behavior that I receive? Why can't I access the articles through the ListItemData.member method as described in the documentation?

    Note: some minor code changes have been made for length and clarity, the code has no compiler errors and like I said the DataModel code works at least to a certain extent all the data members that I expect to be accessible in ListItemData are available in _contentView.

    I haven't checked in depth, but the first thing I would try, is to change your function to return 'post' instead of "item", since you have a component for "post".   I will try an example.

    Stuart

  • Write the QList &lt; Message &gt; in the file

    Hi all

    As API ContactService we method contactToVcard, which converts the table QByte contact which may be subsequently written to the file.

    There is none of these methods in the MessageService API

    https://developer.BlackBerry.com/native/reference/Cascades/bb__pim__message__messageservice.html

    Please tell how to write QList in the file that is transformed into a QByteArray

    Thank you best regards &,.

    I've seen some generic qobjects serialization code that writes all their properties just down, just search for "qobject Serialization" or similar.

    for example:
    https://StackOverflow.com/questions/13835197/serializing-my-custom-class-in-Qt

    or
    http://Flavio.Castelli.name/2009/11/30/qjson-easier-serialization-of-QObject-instances-to-JSON/

    and many others. This is not a trivial question, so I doubt you can find the code that allows to solve your task with just copy & paste...

  • analysis of the json file

    {"employees": [
       {
          "employeeNumber": "00697071617",
          "balance": "422,846.58"
       },
       {
          "employeeNumber": "00697071617",
          "balance": "422,846.58"
       }
    ]}
    
    JsonDataAccess jda;
        QVariant jsonva = jda.load(
                QDir::currentPath() + "/app/native/assets/account.json");
    
        QVariantList list = jsonva.toList();
    
    QVariant childJsonva = list.at(0);
            QVariantList childList = childJsonva.toList();
            for (QList::iterator it = childList.begin(); it != childList.end();
                    it++) {
                qDebug() << "unknown stateeee";
                map = it->toMap();
                qDebug() << "unknown state";
                listModel->append(map);
            }
    

    How can I fix part in bold? I'm able to do the loop inside the employees...

    No list is seen... application crashes on the bold part...

    I have try other ways... I am never able to get to the loop inside employees

    solved

    QVariantMap childJsonv1a = list.toMap();
            QVariant  childJsonva = childJsonv1a["employees"];
            QVariantList childList = childJsonva.toList();
    

    get it in qvariantmap

  • 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...

  • Problem in parsing Json

    I have a problem with parsing Json. While participating in the 1st time I would log on to the Console as

    "Jsonva length 21".
    JSON length 0 "

    After 2 or 3 attempts, I would log in the form

    "Jsonva length 21".
    JSON length 14 "

    Here I use to code analysis.

    BB::data :: JsonDataAccess ja;
    const QVariant jsonva = ja.loadFromBuffer (response);
    QList const externalip = jsonva.toList ();

    std::cout< "jsonva="" length1="" "="">< jsonva.size=""><>
    std::cout< "json="" length1="" "="">< externalip.size()=""><>

    Pls advice me what is the problem in my code.

    Sorry that was my problem. I have error in functionality.

    Thanks dude.

  • 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.

  • "Failed to process the backup file" - bookmarks JSON file

    I deleted my appdata files without thinking and then allowed my trash. When I opened firefox again all my favorites have disappeared. I used piriform recuva to find my deleted files and recover the backup JSON files 10 bookmark. When I try to restore my bookmarks, I get the message "failed to process the backup file". "Files are 95 KB in size, but when I open them with Notepad that they are empty, however, when you use the Restore tool, it is said ' elements of 480", which I assume is the amount of bookmarks, I had, which means that firefox can see data. The same happens for all ten backups that I recovered.

    Any help would be appreciated.

    What is the name of this file?

    Firefox can only look at the file name for the number of items.

    • < number > _ < hash > .json bookmark-YYYY-MM-JJ_

    The files in the bookmarkbackups folder are currently in compressed format .jsonlz4 (i.e., they show data binary like a ZIP compressed archive) and cannot be easily unzipped for access the JSON text format.
    The files are compressed means that a single error in the file will make it impossible to unpack the file.

    Have you checked all the available JSON backup to see if everything works?

    A backup created manually JSON is always not compressed, so can be easily inspected or opened in a text editor (Notepad > "Pretty Print"), but with a compressed file, it is much more difficult.

    Recovery of a file via an undelete utility is no guarantee that the space occupied by the file has not been used by another file, and so is corrupt.

  • differences in the use of a backup Favorites file ".json" and a file of bookmarks '.html '.

    Hi all
    What is the difference between the use of a backup Favorites file ".json" and a file of bookmarks ".html"? It seems that both of them do the same job. If this is the case, then why there are two options (.json and .html) to do the same job? If this isn't the case, then what is the reason for the availability of the two options and how are they different? Although I read the material, it didn't quite clear form me again. Please be so kind enough to elaborate on the question so that I can get a clear understanding of their good use (s).
    Thank you very much in advance for your time and skills

    Hello

    See questions/684284

  • Cannot import a brand book .json file (a file HTML BM or BM Chrome)

    Started FF with no plugins and he locked up tight when you try to import a json file has recently made my PC who died.
    Did the same thing with less desirable HTML bookmarks or import Chrome bookmarks.

    This behavior of shit years and followed me across 5 or 6 PC...

    In a similar thread a year or two there, after much back and forth, the user has finished by reports that finally restored Firefox bookmarks successfully and unlock after being greeted a long period of time to complete the operation.

    I don't know how long you let go but maybe give it 10 minutes and see if that helps? You can open the task manager of Windows 7 (Ctrl + Shift + Esc) in the processes tab, monitor that Firefox is active or dead.

Maybe you are looking for

  • iTunes message: don't forget you need to update your iTunes account!

    Confirm your account! Dear Member, We have faced some problems with your account, please confirm your billing information, if you do not confirm your account within 72 hours, it will be closed from Permenatly! To update your account, just to confirm

  • Contact ID on my iPhone 6 s does not work although it is on pricing

    Contact ID does not work when my iphone 6s is in charge that I bought 09/12/15.

  • Array of string to a shared variable

    I'm writing a table 1 d of channels to a variable published network shared, but apparently not to write it. On the host, I can read the variable after that I write for her, but I can't read it on the remote system (real time). It's always empty. I ch

  • Very slow E3200 with Comcast:

    Hello First of all, there was a similar thread here two years, but no solution has been provided so I'm starting a new. I am one of those fellows who have a surfboard 6141 + E3200 and a connection from comcast of 50Mbps, installed yesterday. Strangel

  • Media Center IR is not recognized in Windows 7 (64-bit)

    Hello I have a HP m8300f desktop computer.  I bought the HP media center unit and the remote, but it is not recognized in Windows 7 (64-bit). I have no problem plug on my netbook acer, its recognized and works fine (Windows 7 32 bit) Impossible to fi