Ted
Ted

Reputation: 3875

Parsing JSON using SBJSON, issue

I am getting a JSON response in a predicted form. so that the tree looks like this:

{ "data":{
           "img":"image":"http:\/\/testingpage.com\/images\/frog_320x480_23.jpg",      
           "link":"http:\/\/google.com","verbose":"Hi there"}, 
           "figures":[ 
                       { "ID":"16","TYPE":"sailor","COLOR":"1E90FFFA","ICON":"sailor"},
                       {"ID":"32","TYPE":"pilot","COLOR":"32CD32BC","ICON":"pilot"}
                     ]
          }
}

I am using the SBJSON library.
I am getting my values with

NSString *jsonString = [[NSString alloc] initWithData:iData encoding:NSUTF8StringEncoding]; NSDictionary *results = [jsonString JSONValue];

and getting the keys I need with:

results objectForKey:@"keyname"]

so far so good.

What just happened now is that I am getting a response from a different provider and the result is completely different in it's nature:

[
     { "TEMPValues": {
                   "temp1": 13.2,
                   "temp2":11.1, 
                   "temp3":11.2,
                   "temp4":13.4
                 }, 
       "semipath":"pollution", 
       "value":"AXT" 
      },
      { "TEMPValues": {
                   "temp1":19.3,
                   "temp2":12.1, 
                   "temp3":10.8,
                   "temp4":13.1}, 
        "semipath":"pollution",
        "value":"AUT"
      }
]

I have two problems here:

  1. I don't know how to access these values as they are in the root, an array. and that array has no key that I can refer to. So What should the approach be with that kind of structure? If I need to get the temp1 of the first object of TEMPValues in the array.

  2. Whenever I try to get a value using results objectForKey:@"keyname"] I get a SIGABRT because results is recognised an array

Upvotes: 0

Views: 70

Answers (2)

Shanthanu
Shanthanu

Reputation: 421

You u have to make similar like this.

  -(void) retrieveData{
       NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"yoururl"]];

      [request setHTTPMethod:@"GET"];

      [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"TEMPValues"];

      NSError *err;

      NSURLResponse *response;

      NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

      NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];


     variable=[[jsonArray objectAtIndex:0]objectForKey:@"keyname"];
   }

Upvotes: 1

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

First Create array of values

NSArray *results = (NSArray *)[jsonString JSONValue];

After that iterate this array

for(int i= 0; i < results.count; i++) {
    NSDictionary *dic = (NSDictionary *)[results objectAtIndex:i];
}

Upvotes: 1

Related Questions