0

Hi I'm having trouble with JSON deserialization.

I am using SBJson, the data is returned from a .net webservice.

This is the returned JSON (shortened)

{
    "id": "1",
    "result": [
        {
            "questionID": 21,
            "question": "What is the secret of eternal life?"
        },
        {
            "questionID": 20,
            "question": "What is the meaning of life?"
        }
    ]
}

I have got so far using the following code

-(void) dataLoaded:(NSData*)data {

    NSString* jsonString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];

    NSDictionary *jsonObject = [jsonString JSONValue];    

        NSLog(@"data : %@", [jsonObject valueForKey:@"result"]);
 }

The following line [jsonObject valueForKey:@"result"] returns the following data

(
        {
        question = "What is the secret of eternal life?";
        questionID = 21;
    },
        {
        question = "What is the meaning of life?";
        questionID = 20;
    }
)

how do i get that data into an array?

This is the first time i've used Json so i'm not totally sure what's going on.

Thanks Mick

user551353
  • 79
  • 1
  • 6

1 Answers1

1

You are getting an array back already... You could use something like this to create a pointer to this array:

NSDictionary *jsonObject = [jsonString JSONValue];
NSArray *myJsonArray = [jsonObject valueForKey:@"result"];

EDIT (After some comments)

Since you're logging the [jsonObject valueForKey:@"result"] and NSLog prints you what you have posted, its certain that the object is an NSArray.

You can count and log like this (notice the %d):

int c = [myJsonArray count];
NSLog("My array's count is: %d", c);
Alladinian
  • 34,483
  • 6
  • 89
  • 91
  • Thanks for the reply, i tried that earlier by using the following 'code'NSArray* questions = [jsonObject valueForKey:@"result"];'code' when i tried to get the array size the app bombed out. – user551353 May 02 '12 at 11:42
  • What do you mean 'bombed out'? How did you try to get the size? – Alladinian May 02 '12 at 11:52
  • Sorry i meant crashed, i used the following line `int tmp = [questions count];` – user551353 May 02 '12 at 11:59
  • ok and then crashed on that line or when you (maybe) tried to `NSLog` that value? – Alladinian May 02 '12 at 12:01
  • Hi Alladinian, just saw your edit. I'm not at my MAC at the moment (it's at home) but i'm not sure how your suggestion could work. isnt my `int tmp = [questions count];` the same as your `int c = [myJsonArray count];`? if my line crashed the app surely yours would too? – user551353 May 02 '12 at 12:19
  • Yes it's the same. My doubt is not on that line. There could be 2 reasons to crash the app by trying to count the array: Either the Array is unallocated or you have tried to log an `int` with `%@`. Anyway try it when you can get your hands on. – Alladinian May 02 '12 at 12:26