Parsing JSON Array in iOS with JSONKit - array with no tag for ObjectForKey?
Asked Answered
S

2

5

I am trying to parse a JSON array returned by a RESTful web API that looks similiar to the following (using JSONKit):

[ { "DateCreated" : "/Date(1320296400000)/",
    "ID" : 1,
    "Summary" : "Summary 1",
    "Title" : "Title 1",
    "URL" : "URL 1"
  },
  { "DateCreated" : "/Date(1320296400000)/",
    "ID" : 2,
    "Summary" : "Summary 2",
    "Title" : "Title 2",
    "URL" : "URL 2"
  }
]

The JSON I have worked with the the past usually had a parent element, for example news:{{node1},{node2}}, that would allow me to extract that node from the JSON response, like this:

NSString *response = [request responseString];
NSDictionary *deserializedData = [response objectFromJSONString];
NSArray *arrNews = [deserializedData objectForKey:@"news"];

In my JSON, no such node exists, it is simply a raw array. How do I go about pulling this into an NSArray (or something I can hook into a UITableView)?

Sleigh answered 12/12, 2011 at 0:16 Comment(0)
K
10

From the looks of your JSON data, it looks like your deserializedData should already be a JKArray filled with JKDictionary objects.

Have you tried accessing it like an array ?

for (NSDictionary * dataDict in deserializedData) {
    NSString * timeStamp = [dataDict objectForKey:@"DateCreated"];
    // and so on
}

This should loop you through every single element in the JSON data.

Korella answered 12/12, 2011 at 1:40 Comment(2)
So how do you know it's array element 0 he's interested in?Frenetic
I updated my answer so that no specific index is accesed, avoiding the 0 confusion.Korella
F
1

A legal JSON string can have, as its outer "container", either an array or a dictionary/"object". The JSON in your sample has an array as the outer "container". Perfectly legit.

If you don't know which to expect you have to test the object to see which it is.

Frenetic answered 12/12, 2011 at 1:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.