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);
Related
I am new to iOS development. I am trying to covert JSOn array values to Objective-C values. My JSON values are like this:
{"result":
[{"alternative":
[{"transcript":"4"},
{"transcript":"four"},
{"transcript":"so"},
{"transcript":"who"}],
"final":true}],
"result_index":0}
I have tried it this way:
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:speechrequestString]];
NSError *error;
NSDictionary *speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray= [speechResult valueForKey:#"result"];
NSLog(#"%#",speechArray);
NSLog(#"Response is of type: %#", [speechArray class]);
speechArray is always null. How to resolvee this problem?
At the same time I would like to print transcript values.
I think the problem might be in initializing the array and Dictionary.
Try doing this,
NSDictionary *speechResult = [NSDictionary new];
NSArray *speechArray = [NSArray new];
Hope it helps..
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];//data is your response from server as NSData
if ([json isKindOfClass:[NSDictionary class]]){ //Added instrospection as suggested in comment.
NSArray * speechArray = json[#"result"];
}
NSLog(#"speech array %#",speechArray);
Did you check the value in NSDictionary (speechResult).
If it is nil, check the json data isValid or not.
NSError *error;
if ([NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error] == nil)
{
// Check the error here
}else {
// here check whether it is a dictionary and it has key like #Bhadresh Mulsaniya mentioned.
}
If returns nil, then you check the error to understand what's wrong.
try this may be it will help you:-
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:speechrequestString]];
NSError *error;
NSDictionary *speechResult = [NSDictionary new];
speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray = [[NSArray alloc]init];
speechArray= [speechResult valueForKey:#"result"];
NSLog(#"%#",speechArray);
NSLog(#"Response is of type: %#", [speechArray class]);
try this code,
restaurantdictionary = [NSJSONSerialization JSONObjectWithData:mutableData options:NSJSONReadingMutableContainers error:&e];
NSMutableArray *main_array=[[NSMutableArray alloc]init];
main_array=[restaurantdictionary valueForKey:#"results"];
NSLog(#"main_array %#", main_array);
its working for me, hope its helpful
You have to initialize the array before using it,
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:speechrequestString]];
NSError *error;
NSDictionary *speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray= [[NSArray alloc] init];
speechArray= [speechResult valueForKey:#"result"];
if (speechArray.count>0) {
NSDictionary * alternativeDictn = [speechArray objectAtIndex:0];
NSArray *alternativeAry= [[NSArray alloc] init];
alternativeAry = [alternativeDictn objectForKey:#"alternative"];
NSLog(#"%#",alternativeAry);
}
NSLog(#"Response is of type: %#", [speechArray class]);
Using this code you will get following result,
(
{
transcript = 4;
},
{
transcript = four;
},
{
transcript = so;
},
{
transcript = who;
}
)
Try out the below code to get the transcripts:
NSData* jsonData = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *responseObj = [NSJSONSerialization
JSONObjectWithData:jsonData
options:0
error:&error];
if(! error) {
NSArray *responseArray = [responseObj objectForKey:#"result"];
for (NSDictionary *alternative in responseArray) {
NSArray *altArray = [alternative objectForKey:#"alternative"];
for (NSDictionary *transcript in altArray) {
NSLog(#"transcript : %#",[transcript objectForKey:#"transcript"]);
}
}
} else {
NSLog(#"Error in parsing JSON");
}
You should alloc your dictionary first like this-
NSDictionary *speechResult = [[NSDictionary alloc]init];
speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray = [[NSArray alloc]init];
speechArray= [speechResult valueForKey:#"result"];
I have a dictionary that looks like this.
NSDictionary *dict = #{#"cpu" : self.proData ,
#"date" : timeMilliString,
#"memory" : self.memData,
#"battery" : self.batData,
#"deviceID" : #"1"
};
I'm creating json objects from it like this:
self.jsonObj1 = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
self.jsonObj2 = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
self.jsonObj3 = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
Afterwards I want to put the 3 json objects into a json array and then put that json array into another json object. So finally, it should look something like this:
{"mobileData":[
{ "cpu":-991,
"date":"142441374.5834",
"memory":978,
"battery":-96,
"deviceID" : 2
},
{ "cpu":-51,
"date":"142441374.5834",
"memory":978,
"battery":-96,
"deviceID" : 2
},
{ "cpu":-51,
"date":"142441374.5834",
"memory":978,
"battery":-96,
"deviceID" : 2
}
]
}
I have tried it as follows but it's not working.
NSArray *jsonArray = #[self.jsonObj1, self.jsonObj2, self.jsonObj3];
NSDictionary *dict = #{#"mobileData" : jsonArray};
if ([NSJSONSerialization isValidJSONObject:dict])
{
// Serialize the dictionary
json = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error2];
// If no errors, let's view the JSON
if (json != nil && error2 == nil)
{
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#", jsonString);
//[jsonString release];
}
}
I'm getting an exception.
Any ideas? Thanks.
Firstly add all dictionaries to a array.
NSMutableArray *mutArrData = [NSMutableArray array];
//Add dictionaries which vary to your requirement.
[mutArrData addObject:yourDictionary]; //1
[mutArrData addObject:yourDictionary]; //2
[mutArrData addObject:yourDictionary]; //3
Now create a main dictionary to add array.
NSDictionary *dictJsonData = [NSDictionary dictionaryWithObjectsAndKeys:[mutArrData mutableCopy],#"mobileData",nil];
Now create json from dictionary
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictJsonData options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData && !error)
{
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#", jsonString);
}
The code:
NSURL * url=[NSURL URLWithString:#"alamghareeb.com/mobileData.ashx?catid=0&No=10"];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary * json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSMutableArray * referanceArray=[[NSMutableArray alloc]init];
NSMutableArray * periodArray=[[NSMutableArray alloc]init];
NSArray * responseArr = [NSArray arrayWithArray:json[#"item"]];
for (NSDictionary * dict in responseArr) {
[referanceArray addObject:[dict objectForKey:#"created"]];
}
The JSON looks like:
{
"item" = [
{
"id" : "2292",
"created" : "10/01/2015 10:21:18 ص",
"title" : "الإمارات: ملابس رياضية فاخرة لتحسين أداء الإبل في السباقات ",
"image_url" : "http://alamghareeb.com/Photos/L63556482078696289044.jpg",
"image_caption" : ""
},
{
"id" : "2291",
"created" : "10/01/2015 09:28:11 ص",
"title" : "طبيبة تجميل 'مزورة' تحقن مرضاها بالغراء والاسمنت",
"image_url" : "http://alamghareeb.com/Photos/L63556478891290039015.jpg",
"image_caption" : ""
}
]
}
This JSON is not valid. Did you build it manually? The "item" = ... should be "item" : ....
In the future, you can run your JSON through http://jsonlint.com to verify any issues. Likewise, you should add error checking in your Objective-C code, e.g.
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
if (!json) {
NSLog(#"JSON parsing error: %#", error);
}
I'd also suggest changing your server code to not build JSON manually, but take advantage of JSON functions (e.g. if PHP, build associative arrays and then generate JSON output using the json_encode function).
So, once you fix the JSON error, to parse the results might look like:
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (!dictionary) {
NSLog(#"NSJSONSerialization error: %#", error);
return;
}
NSArray *items = dictionary[#"item"];
for (NSDictionary *item in items) {
NSString *identifier = item[#"id"];
NSString *created = item[#"created"];
NSString *title = item[#"title"];
NSString *urlString = item[#"image_url"];
NSString *caption = item[#"image_caption"];
NSLog(#"identifier = %#", identifier);
NSLog(#"created = %#", created);
NSLog(#"title = %#", title);
NSLog(#"urlString = %#", urlString);
NSLog(#"caption = %#", caption);
}
You can use NSJSONSerialization. No need to import any class.
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[strResult dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
or use NSData directly as
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:theJSONDataFromTheRequest options:0 error:nil];
Source : Stackoveflow question
I need to get Particular Object values ( A, B, C, D) and related key values (#"name" ). Here below I have posted my sample code and response. Please help me.
NSString *combined = URL;
NSURL *url = [[NSURL alloc] initWithString:combined];
NSData *responseData=[NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray *responsData = [jsonDictionary objectForKey:#"response"];
// GET A,B,C Object values
NSDictionary *d1 = responsData.firstObject;
NSEnumerator *enum1 = d1.keyEnumerator;
NSArray *firstObject = [enum1 allObjects];
My JSON Response :
response : [ {
A = [ {
name : tango
}
{
name : ping
}
]
B = [ {
name : tango
}
{
name : ping
}
]
} ]
You can achieve the list of all names using this:
NSMutableArray *names = [[NSMutableArray alloc] init];
for (NSDictionary *dict in responsData) {
[dict enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
NSArray *valueArray = (NSArray *)obj;
for (NSDictionary * namesDict in valueArray) {
[names addObject:namesDict[#"name"]];
}
}];
}
Output:
NSLog(#"Names %#",names);
tango, ping, tango, ping.
Hope that helps!
Simply
for(NSDictionary *dict in firstObject){
NSLog(#"%#",[dict objectForKey:#"name"]);
}
I am new in the iOS development and i am calling the web service that returns me data like
[
{
"ID": "3416a75f4cea9109507cacd8e2f2aefc3416a75f4cea9109507cacd8e2f2aefc",
"Name": "2M Enerji"
},
{
"ID": "072b030ba126b2f4b2374f342be9ed44072b030ba126b2f4b2374f342be9ed44",
"Name": "Çedaş"
},
{
"ID": "093f65e080a295f8076b1c5722a46aa2093f65e080a295f8076b1c5722a46aa2",
"Name": "Çelikler"
},
{
"ID": "7cbbc409ec990f19c78c75bd1e06f2157cbbc409ec990f19c78c75bd1e06f215",
"Name": "Çoruh EDAŞ"
},
{
"ID": "70efdf2ec9b086079795c442636b55fb70efdf2ec9b086079795c442636b55fb",
"Name": "İçdaş"
}
]
Now i am trying to get it in the array , the array will be seperate for the name and id , i am done till taking in NSDICT following is my code
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"finish loading");
NSString *loginStatus = [[NSString alloc] initWithBytes:[webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
NSString *responsewith = [[NSString alloc] initWithData:webData
encoding:NSUTF8StringEncoding];
//providerData = [NSKeyedUnarchiver unarchiveObjectWithData:webData];
providerDropData = [NSString stringWithFormat:responsewith];
NSLog(#"drop %#",providerDropData);
NSArray *providerData = [providerDropData valueForKey:#"ID"];
NSLog(#"jey %#",responsewith);
NSLog(#"resonser %#",responsewith);
NSLog(#"laoding data %#",loginStatus);
//greeting.text = loginStatus;
[loginStatus release];
[connection release];
[webData release];
}
When i tried saving the NSDictionary to the NSArray for #"ID" the application get crashed.
Please help
You simply want to use NSJSONSerialization
NSError *error = nil;
NSArray *results = [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
if (!results)
NSLog(#"%s: JSONObjectWithData error: %#", __FUNCTION__, error);
// get the first provider id
NSString *providerData = results[0][#"ID"];
You can fetch data from JSON like below way as well,
id jsonObjectData = [NSJSONSerialization JSONObjectWithData:webData error:&error];
if(jsonObjectData){
NSMutableArray *idArray = [jsonObjectData mutableArrayValueForKeyPath:#"ID"];
NSMutableArray *nameArray = [jsonObjectData mutableArrayValueForKeyPath:#"Name"];
}
Convert the data to NSDictionary by parsing, then you can extract using KVP.
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:response options:0 error:&error];
NSDictionary * providerDropData = [NSJSONSerialization JSONObjectWithData:webData error:&error];
NSLog(#"drop %#",providerDropData);
NSMutableArray *providerData = [NSMutableArray new];
NSString *key = #"ID";
for (key in providerDropData){
NSLog(#"Key: %#, Value %#", key, [providerDropData objectForKey: key]);
[providerData addObject:[providerDropData objectForKey:key]];
}
NSLog("ID Array = %#", providerData]);
}