Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Native Development

Reply
Trusted Contributor
Posts: 140
Registered: ‎11-23-2010
My Device: Torch 9800
My Carrier: Rogers
Accepted Solution

Quick help with json file

Hello all,

 

   I'm trying to figure out how to drill down a json file. Here is the structure of the file

 

{
   "company" : 1,
   "employees" : [
      {
         "firstname" : "Tim Tom,
         "more_info" : {
            "address" : "123 lausanne",
            
         }
      }
   ],
   "total" : 750
}

 right now I have employee covered doing it this way.

 

bb::data::JsonDataAccess ja;
QVariant jsonva = ja.loadFromBuffer(response);

QVariantList employeeList = jsonva.toMap().find("employee")->toList();

QVariantMap infoList = jsonva.toMap().find("employee")->toMap().find("more_info")->toMap();

 

So the first one with employee works. I get the data out of it including more_info

but for the second one that doesn't seem to work. Is it because I need to loop through my first list?

 

Thank you for the help

 

 

Highlighted
Developer
Posts: 1,524
Registered: ‎12-18-2012
My Device: Z30, Z10 LE, DevAlpha C, PlayBook

Re: Quick help with json file

Hi,

Iterate the list using foreach:

 

QVariantList employeeList = jsonva.toMap()["employees"].toList();

foreach (QVariant v, employeeList)
{
  QVariantMap employeeData = v.toMap();
  QVariantMap moreInfo = employeeData["moreInfo"];
}

An important point to note is that find() function can potentially return mapName.end() if the name wasn't found in map. If you don't check for this case explicitly the application will crash on malformed input.

 

Another option which I'm using above is using operator[] which creates the value for key if it's missing and always returns a valid reference to the value, so it's not neccessary to validate the result.

 


Andrey Fidrya, @zmeyc on twitter
Trusted Contributor
Posts: 140
Registered: ‎11-23-2010
My Device: Torch 9800
My Carrier: Rogers

Re: Quick help with json file

Thank you for the answer it's really appreciated. I would like to add another thank you for going a bit further then the question and give me a little hint about the find function. I'm barely starting here and it's really nice to have tips like that.

So thank you again.