I have some NSData coming back from my server that is of type Json. I would like to know how to access the values present in the json and put them into there own NSString objects.
This is what the structure of the JsonArray looks like
This is the code I am using, however my for loop only ever shows "result" and nothing else.
NSError *error = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:csvData options: NSJSONReadingMutableContainers error: &error];
NSLog(#"%#", jsonArray);
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#", error);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(#"Item: %#", item);
}
}
You can access it like that:
for (NSDictionary *dict in jsonArray)
{
NSLog(#"Data: %#", dict[#"result"]);
}
You have dictionary in your array so you have to enumerate is and access it by key (result, etc.).
NSDictionary *resultDictionary = [jsonArray objectAtIndex: 0];
NSArray *resultArray = [resultDictionary objectForKey:#"result"];
for (NSString *item in resultArray)
{
NSLog (#"item: %#",item);
}
You should add some (non)sense checking.
u can access the json array like this,
for(NSDictionary *Mydictionary in MyJsonArray) {
Nsstring *DataOne = [Mydictionary objectforkey#"Mykey"];
}
For Cheking the json node u can put the json in this site and all the node will appear properly
http://json.parser.online.fr/
Related
I have got json response like following
Photo = ["\image1.jpg\","\image2.jpg\","\image3.jpg\"]
How can i get only name from this json response.
I want output like
Image1.jpg
Image2.jpg
Image3.jpg
Without [] and "".
First of all, Your Photo String is not in proper format. The correct String is as follows:
NSString *jsonString = #"[\"\image1.jpg\",\"\image2.jpg\",\"\image3.jpg\"]";
Try out the below code to get image name from Your String:
NSString *jsonString = #"[\"\image1.jpg\",\"\image2.jpg\",\"\image3.jpg\"]";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e = nil;
NSArray *json = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
if (!json) {
NSLog(#"Error parsing JSON: %#", e);
} else {
NSLog(#"Item: %#", json);
for(NSString *item in json) {
NSLog(#"Item: %#", item);
}
}
it's possible by using IF to retrieve some parts of JSON not all of it in Objective-C. like i want to retrieve just those data when Gender equals Male
[
{
"name":"A",
"gender":"Male",
"age":20
},
{
"name":"B",
"gender":"Female",
"age":12
},
{
"name":"C",
"gender":"Male",
"age":20
}
]
any idea would be appreciated.
using for in loop
for (NSDictionary *dict in JSONArray) {
if ([dict[#"gender"] isEqualToString:#"Male"]) {
NSLog(#"Gender Data: Name = %# Age = %#", dict[#"name"], dict[#"age"]);
}
}
alternative solution with NSPredicate
NSString *jsonString = #"[{\"name\":\"A\",\"gender\":\"Male\",\"age\":20},{\"name\":\"B\",\"gender\":\"Female\",\"age\":12},{\"name\":\"C\",\"gender\":\"Male\",\"age\":20}]";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error: nil];
NSArray *maleRecords = [jsonArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"gender == 'Male'"]];
NSLog(#"%#", maleRecords);
I am trying to loop over a neatest NSDictionary within a NSDictionary.
currently I have this and this returns the first NSDictionary items
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response
for (NSString *tempObject in json ) {
NSLog(#"Single element: %#", tempObject);
}
The Above works fine
however I wish to read a array layer lower and the blow is failing,
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
for (id tempObject in json ) {
NSLog(#"Object: %#, Key: %#", [json objectForKey:tempObject], tempObject);
}
Thanks Mich
It's always good to check whether the deserialized object contains ARRAY or DICTIONARY within. You can check the type of object before trying to access it. Something like this.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
for (id jsonObject in json ) {
NSLog(#"Object: %#, Key: %#", [json objectForKey:tempObject], tempObject);
if ([jsonObject isKindOfClass:[NSDictionary class]]){
NSDictionary *deserializedDictionary = jsonObject;
NSLog(#"Deserialized JSON Dictionary = %#",
deserializedDictionary);
}
else if ([jsonObject isKindOfClass:[NSArray class]]){
NSArray *deserializedArray = (NSArray *)jsonObject;
NSLog(#"Deserialized JSON Array = %#", deserializedArray);
}
else {
/* Some other object was returned. We don't know how to
deal with this situation as the deserializer only
returns dictionaries or arrays */
}
}
Hope it helps you!!
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
for (NSString *tempObject in json ) {
NSLog(#"Object: %#, Key: %#", [json objectForKey:tempObject], tempObject);
NSLog(#"Object: %#, Key: %#", [json valueForKey:tempObject], tempObject);
}
//OR by using fast enumeration
[json enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {
NSLog(#"####Key Value is:%# = %#", key, object);
}];
Hope it helps you....!
I have a for loop going through a dictionary of dictionaries. It works just fine unless there is only one dictionary total.
Here's the gist of my method:
- (NSArray *)objectsFromJSON:(NSString *)jsonString error:(NSError **)error
{
NSParameterAssert(jsonString != nil);
// create JSON object
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *localError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&localError];
NSDictionary *dictionaryOfDictionaries = (id)jsonObject;
// if not parsed successfully, error
if(dictionaryOfDictionaries == nil)
{
if(error != NULL)
{
*error = [NSError errorWithDomain:ErrorDomain code:MissingDataError userInfo:nil];
}
return nil;
}
// else create objects out of parsed data
NSMutableArray *objectsArray = [NSMutableArray array];
for(NSDictionary *objectDictionary in dictionaryOfDictionaries)
{
// required properties
Obj *object = [[Obj alloc]
initWithName:objectDictionary[#"name"]
Street:objectDictionary[#"street"]
City:objectDictionary[#"city"]
State:objectDictionary[#"state"]
];
// if error, return
if(object == nil)
{
if(!error)
{
*error = [NSError errorWithDomain:ErrorDomain code:MissingDataError userInfo:nil];
}
return nil;
}
// else add to array of objects created successfully
[objectsArray addObject:object];
}
return [objectsArray copy];
}
As mentioned, this works fine - i.e. all of the objects are created successfully out of the objectDictionary - if there's more than one dictionary in dictionaryOfDictionaries. However, if there is just one dictionary, objectDictionary ends up being type id in the for loop (instead of type Obj), and trying to access its values, such as objectDictionary[#"name"] results in an error.
How do I most efficiently write this so the case of having one dictionary is handled?
Here's the issue. When you have more than one dictionary, you actually get an array of dictionaries. In other words, jsonObject is really an NSArray containing each of the dictionaries.
When there is just one dictionary, jsonObject is just that one dictionary.
Change your code like this:
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&localError];
NSArray *arrayOfDictionaries = nil;
if (jsonObject == nil) {
// handle error
} else if ([jsonObject isKindOfClass:[NSArray class]]) {
arrayOfDictionaries = jsonObject;
} else {
arrayOfDictionaries = #[ jsonObject ];
}
Then change the for loop to:
for(NSDictionary *objectDictionary in arrayOfDictionaries)
Create Array from json response that would be dictionaries
NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if (error)
NSLog(#"JSONObjectWithData error: %#", error);
for (NSMutableDictionary *dictionary in array)
{
//Do what you want to do
}
Hi I have the following json that i need to parse, however, I'm struggling to parse the inner array. What I have currently just prints each of the inner arrays but I'd like to print say each title and add the titles to an array. Thank you for any help!
JSON
{"nodes":[{
"node":{
"nid":"1420857",
"title":"Title 1",
"votes":"182",
"popular":"True",
"teaser":"Teaser 1"
}},
{"node":{
"nid":"1186152",
"title":"Title 2",
"votes":"140",
"popular":"True",
"teaser":"Teaser 2"
}},
{"node":{
"nid":"299856",
"title":"Title 3",
"votes":"136",
"popular":"True",
"teaser":"Teaser 3"
}}
]}
Json Parser
NSError *error = nil;
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.somefilename.json"]];
if (jsonData) {
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(#"error is %#", [error localizedDescription]);
return;
}
NSArray *keys = [jsonObjects allKeys];
for (NSString *key in keys) {
NSLog(#"%#", [jsonObjects objectForKey:key]);
}
} else {
// Handle Error
}
Just typecast it:
NSArray *nodes = (NSArray*)[jsonObjects objectForKey:#"nodes"];
for (NSDictionary *node in nodes){
// do stuff...
}
Methods that return id (like -[objectForKey:], and -[objectAtIndex:]) can return any objective-c object. You'll need to know ahead of time what to typecast it into to perform the appropriate operations on it. JSON is converted to the NSObject equivalents:
object -> NSDictionary
array -> NSArray
string -> NSString
number -> NSNumber
boolean -> NSNumber
float -> NSNumber
null -> NSNull
To differentiate between the various NSNumbers, you'll have to call the appropriate type method: -[intValue], -[boolValue], -[floatValue]. Check out the NSNumber docs for more info.
You can use my method for json parsing,
Parse Method:
-(void)jsonDeserialize:(NSString *)key fromDict:(id)content completionHandler:(void (^) (id parsedData, NSDictionary *fromDict))completionHandler{
if (key==nil && content ==nil) {
completionHandler(nil,nil);
}
if ([content isKindOfClass:[NSArray class]]) {
for (NSDictionary *obj in content) {
[self jsonDeserialize:key fromDict:obj completionHandler:completionHandler];
}
}
if ([content isKindOfClass:[NSDictionary class]]) {
id result = [content objectForKey:key];
if ([result isKindOfClass:[NSNull class]] || result == nil) {
NSDictionary *temp = (NSDictionary *)content;
NSArray *keys = [temp allKeys];
for (NSString *ikey in keys) {
[self jsonDeserialize:key fromDict:[content objectForKey:ikey] completionHandler:completionHandler];
}
}else{
completionHandler(result,content);
}
}
}
Method Call:
NSData *content = [NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:#"Sample" ofType:#"json"]];
NSError *error;
//to get serialized json data...
id dictionary = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:&error];
//get data for key called GetInfo
[self jsonDeserialize:#"GetInfo" fromDict:dictionary completionHandler:^(id parsedData, NSDictionary *fromDict) {
NSLog(#"%# - %#",parsedData,fromDict);
}];