Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parsing JSON object in iPhone SDK (XCode) using JSON-Framework

I have JSON object like this :

{ "data":
  {"array":
    ["2",
       {"array":
          [
            {"clientId":"1","clientName":"Andy","job":"developer"},
            {"clientId":"2","clientName":"Peter","job":"carpenter"}
          ]
        }
     ]
   },
 "message":"MSG0001:Success",
 "status":"OK"
}

I want to get the array[0] value (2) and array[1] value (clientId, clientName, job) using JSON-Framework. Do you have any idea how to do that?

like image 800
inot Avatar asked Jul 02 '10 11:07

inot


People also ask

What is JSON parsing in iOS?

JSON parsing in Swift is a common thing to do. Almost every app decodes JSON to show data in a visualized way. Parsing JSON is definitely one of the basics you should learn as an iOS developer. Decoding JSON in Swift is quite easy and does not require any external dependencies.

How do I parse a JSON file?

If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method. If you need to parse a JSON file that returns a dictionary, then you can use the json. load() method.

What is JSON parse () method?

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.


2 Answers

Assuming you've followed the instructions to install JSON-Framework into your project, here's how you use it (taken from the docs here) :

// Parse the string into JSON
NSDictionary *json = [myString JSONValue];

// Get the objects you want, e.g. output the second item's client id
NSArray *items = [json valueForKeyPath:@"data.array"];
NSLog(@" client Id : %@", [[items objectAtIndex:1] objectForKey:@"clientId"]);
like image 67
deanWombourne Avatar answered Sep 28 '22 13:09

deanWombourne


thank you for your answer, my problem solved, I modify a little bit from your code, here are:

// Parse the string into JSON
NSDictionary *json = [myString JSONValue];

// Get all object
NSArray *items = [json valueForKeyPath:@"data.array"];
NSArray *array1 = [[items objectAtIndex:1] objectForKey:@"array"];
NSEnumerator *enumerator = [array1 objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
   NSLog(@"clientId = %@",  [item objectForKey:@"clientId"]);
   NSLog(@"clientName = %@",[item objectForKey:@"clientName"]);
   NSLog(@"job = %@",       [item objectForKey:@"job"]);
}
like image 29
inot Avatar answered Sep 28 '22 13:09

inot