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?
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.
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.
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.
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"]);
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"]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With