How to get particular object values and key values from JSON response? - ios

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"]);
}

Related

Objective C JSON parse from NSMutableArray

I have a JSON like below (getting from an URL)-
{
action :getAllJournal;
data :{
journalList :[{
cancelled : F;
"cust_code" : "700-T022";
"journal_amount" : 2216;
"journal_code" : "JV1603/001";
"journal_date" : "2016-03-15 00:00:00";
"journal_id" : 1;
outstanding : 0;
},
{
cancelled : F;
"cust_code" : "700-0380";
"journal_amount" : 120;
"journal_code" : "JV1605/006";
"journal_date" : "2016-05-31 00:00:00";
"journal_id" : 2;
outstanding : 120;
},
{
cancelled : F;
"cust_code" : "700-T280";
"journal_amount" : 57;
"journal_code" : "JV1609/001";
"journal_date" : "2016-09-22 00:00:00";
"journal_id" : 3;
outstanding : 0;
}
];
};
message = "";
"message_code" = "";
result = 1;}
The code below doing is getting the JSON from URL and storing them in NSMutableArray. Until storing them into array, it's working fine but I'm bit confused with the JSON format and don't know how to get result by a key.
__block NSMutableArray *jsonArray = nil;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:#"http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
{
if (data)
{
id myJSON;
#try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
#catch (NSException *exception) {
}
#finally {
}
jsonArray = (NSMutableArray *)myJSON;
NSString *nsstring = [jsonArray description];
NSLog(#"IN STRING -> %#",nsstring);
NSData *data = [nsstring dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if(jsonObject !=nil){
if(![[jsonObject objectForKey:#"journalList"] isEqual:#""]){
NSMutableArray *array=[jsonObject objectForKey:#"journalList"];
NSLog(#"array: %lu",(unsigned long)array.count);
int k = 0;
for(int z = 0; z<array.count;z++){
NSString *strfd = [NSString stringWithFormat:#"%d",k];
NSDictionary *dicr = jsonObject[#"journalList"][strfd];
k=k+1;
// NSLog(#"dicr: %#",dicr);
NSLog(#"cust_code - journal_amount : %# - %#",
[NSMutableString stringWithFormat:#"%#",[dicr objectForKey:#"cust_code"]],
[NSMutableString stringWithFormat:#"%#",[dicr objectForKey:#"journal_amount"]]);
}
}
}else{
NSLog(#"Error - %#",jsonError);
}
}
}];
From this, I am able to get the JSON successfully. But it's always giving me this error: Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in an object around character 6." UserInfo={NSDebugDescription=No string key for value in an object around character 6.} How can I get all values from journalList? I'm new to iOS, that's why not sure what I'm missing.
id myJSON;
#try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
#catch (NSException *exception) {
}
#finally {
}
jsonArray = (NSMutableArray *)myJSON;
NSString *nsstring = [jsonArray description];
NSLog(#"IN STRING -> %#",nsstring);
NSData *data = [nsstring dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
I'd say: NO and NO.
I wouldn't do a #try/#catch on a NSJSONSerialization, because the real issues are on the error parameter (and they won't throw a NSException for most of the cases). Just check if (data) is quite efficient.
Then, let's say it worked, and you have myJSON.
In fact, myJSON is a NSDictionary, not a NSArray, so the cast is useless and doesn't make sense.
Next issue:
Your are using -description (okay, if you want to debug), but you CAN'T use it to reconstruct AGAIN a JSON. It's not a valid JSON, it's the way the compiler "print" an object, it adds ";", etc.
If your print [nsstring dataUsingEncoding:NSUTF8StringEncoding] and data you'll see that they aren't the same.
For a more readable:
NSString *dataJSONStr = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];, it's clearly not the same structure as your nsstring.
Then, you are redoing the JSON serialization? Why ?
So:
NSError *errorJSON = nil;
NSDictionary *myJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&errorJSON];
if (errorJSON)
{
NSLog(#"Oops error JSON: %#", errorJSON);
}
NSDictionary *data = myJSON[#"data"];
NSArray *journalList = data[#"journalList"]
for (NSDictionary *aJournalDict in journalList)
{
NSUInteger amount = [aJournalDict[#"journal_amount"] integerValue];
NSString *code = aJournalDict[#"journal_code"];
}
There is a dictionary named "data" you're not fetching, represented by {}.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if (!jsonError) {
// Fetch the journalList
NSArray *journalList = json[#"data"][#"journalList"];
// iterate over every entry and output the wanted values
for (NSDictionary *journal in journalList) {
NSLog(#"%# %#", journal[#"cust_code"], journal[#"journal_amount"]);
}
}
json[#"key"] is a short form of [json objectForKey:#"key"] I find easier to read.
That is not a valid JSON. Entries should be separated by comma ,, not semicolon ;
You need to fetch journalList from data.
Try below code:
This is demo code to create array like you:
NSMutableDictionary *jsonObject = [NSMutableDictionary new];
jsonObject[#"action"]= #"";
jsonObject[#"message"]= #"";
jsonObject[#"message_code"]= #"";
jsonObject[#"result"]= #"1";
NSMutableArray *ary1 = [NSMutableArray new];
for(int i=0;i<5;i++)
{
NSMutableDictionary *dd = [NSMutableDictionary new];
dd[#"cancelled"]= #"F";
dd[#"cust_code"]= #"F";
[ary1 addObject:dd];
}
NSMutableDictionary *dicjournal = [NSMutableDictionary new];
[dicjournal setObject:ary1 forKey:#"journalList"];
[jsonObject setObject:dicjournal forKey:#"data"];
This is main Logic:
NSMutableArray *journalList = [NSMutableArray new];
NSMutableDictionary *dic = [jsonObject valueForKey:#"data"];
journalList = [[dic objectForKey:#"journalList"] mutableCopy];
Looks like your JSON is invalid. You can see whether your JSON is correct or not using http://jsonviewer.stack.hu/ and moreover format it. Meanwhile your code is not using "data" key to fetch "journalList" array.
Code : -
NSDictionary *dic = [jsonObject valueForKey:#"data"];
NSMutableArray *arr = [dic objectForKey:#"journalList"];
for (int index=0 ; index < arr.count ; index++){
NSDictionary *obj = [arr objectAtIndex:index];
// Now use object for key from this obj to get particular key
}
Thanks #Larme and #Amset for the help. I was doing wrong the in the NSMutableArray part. The correct version of this code is in the below:
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:#"http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
{
if (data)
{
id myJSON;
#try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
#catch (NSException *exception) {
}
#finally {
}
NSArray *journalList = myJSON[#"data"][#"journalList"];
for (NSDictionary *journal in journalList) {
NSLog(#"%# %#", journal[#"journal_date"], journal[#"journal_amount"]);
}
}
}];

How to retrieve part of JSON file?

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);

How to Parse Nested Dictionary JSON Data in iOS?

i am newbie in iOS Development. i want to parse my this JSON Data into to array First array Contain all Data and Second array Contain only -demopage: array Value.
status: "success",
-data: [
{
mid: "5",
name: "October 2014",
front_image: "http://www.truemanindiamagazine.com/webservice/magazineimage/frontimage/01.jpg",
title: "October 2014",
release_date: "2014-10-01",
short_description: "As the name suggest itself “Trueman India” will cover icons of India. Our national Magazine “Trueman India” is an expansion to our business, i",
current_issue: 0,
-demopage: [
{
link: "http://www.truemanindiamagazine.com/webservice/magazineimage/pageimage/2014/10/01-1413806104.jpg",
page_no: "1"
},
{
link: "http://www.truemanindiamagazine.com/webservice/magazineimage/pageimage/2014/10/2-1413806131.jpg",
page_no: "2"
},
{
link: "http://www.truemanindiamagazine.com/webservice/magazineimage/pageimage/2014/10/3-1413806170.jpg",
page_no: "3"
}
]
}
]
Here my main Dictionary Key is data i want data keey value in my One array and demopage key value in to another array here my two Array is self.imageArray and self.imagesa here my code For that
- (void)viewDidLoad
{
[super viewDidLoad];
[self.collectionView registerNib:[UINib nibWithNibName:#"CustumCell" bundle:nil] forCellWithReuseIdentifier:#"CellIdentifier"];
dispatch_async(kBgQueue, ^{
data = [NSData dataWithContentsOfURL: imgURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
-(void)fetchedData:(NSData *)responsedata
{
NSMutableArray *imagesArray = [[NSMutableArray alloc]init];
if (responsedata.length > 0)
{
NSError* error;
self.json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
if ([[_json objectForKey:#"data"] isKindOfClass:[NSArray class]])
{
NSArray *arr = (NSArray *)[_json objectForKey:#"data"];
[self.imageArray addObjectsFromArray:arr];
[self.storeTable reloadData];
}
self.storeTable.hidden=FALSE;
for (index=0; index<[self.imageArray count]; index++)
{
for(NSDictionary *dict in self.imageArray)
{
imagesArray = [dict valueForKey:#"demopage"];
self.imagesa = imagesArray;
}
NSLog(#"New Demo page array %#",self.imagesa);
}
}
then i get my data key value and it is ok but i got only last index means here my -data key Contain three -demopage key and i get only last -demopage key value i want all -demopage key value in to self.imagesa please give me solution for that.
also my Webservices link is Link
First get -data in NSMutableArray.
NSMutableArray *dataArray = [[NSMutableArray alloc]init];
NSMutableArray *imagesArray = [[NSMutableArray alloc]init];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
dataArray=[json objectForKey:#"data"];
for(NSDictionary *dict in dataArray )
{
imagesArray = [dict valueForKey:#"demopage"];
self.imagesa = imagesArray;
}
[selt.tableView reloadData];
You can give it a try like this:
NSError* error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
NSDictionary *dataDict = [json objectForKey:#"data"];
NSArray *imageArray = [dataDict objectForKey:#"demopage"];
self.imagesa = [NSMutableArray array];
for (NSDictionary *dict in array) {
NSString *imageUrl = [dict objectForKey:#"link"];
[self.imagesa addObject:imageUrl];
}
Then you got imageArray as dataSource for the collectionView.
I would use SBJson library, but not the last 4th version:
pod 'SBJson', '3.2'
Sample code, I changed variable names and formatting a little bit:
// Create a JSON String from NSData
NSData *responseData = [NSData new]; // Here you should use your responseData
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
if (! jsonString ) {
// Handle errors
}
// Create SBJsonParser instance
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
// Parse JSON String to dictionary
NSDictionary *jsonDic = [jsonParser objectWithString:jsonString];
// Get an array by key
NSArray *dicArray = [jsonDic objectForKey:#"demopage"];
// Reload collection view
if ( [dicArray count] > 0 ) {
dispatch_async(dispatch_get_main_queue(), ^{
// Reload Your Collection View Here and use dicArray (in your case imagesa array with dictionaries)
});
}
And when you set a cell, you can use something like this:
NSDictionary *dic = dicArray[indexPath.row];
NSString *link = dic[#"link"];
NSString *pageNo = dic[#"page_no"];

Put value to a json response by using SBJson

I want to add value to a response. But the response is in this format
{
"participants": [
{
"lat_long": "0.0,0.0",
"name": "alma"
}
],
"lat_long": "0.0,0.0",
"_id": "52a80a5dccb8137326000027"
}
How can I add values to the keys name & lat_long. I am using Sbjson method.
Thanks in advance.
NSURL * url=[NSURL URLWithString:#"Give your URL Here"];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary * jsonDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"%#",jsonDic);
NSMutableArray * jsonArray=jsonDic[#"participants"];
NSLog(#"%#",jsonArray);
NSString * str =[jsonArray valueForKey:#"lat_long"];
NSString * str1 =[jsonArray valueForKey:#"name"];
NSLog(#"%#",str);
NSLog(#"%#",str1);
Try this code.
I'm not sure, what you are asking about, but This helps you to get the keys of the Disctionary .
NSDictionary *json = [NSJSONSerialization .....//Parsed JSon
NSMutableDictionary *arrCopy = [json mutableCopy];
NSArray *keys= [json allKeys];
for (NSString *keysV in keys){
NSLog(#"Keys are %#", keysV);
if ([keysV isEqualToString:#"_id"]) {
[arrCopy setValue:#"121213211323" forKey:keysV];
}else if (){
}.......................
}
NSLog(#"After Value added: %#", arrCopy);

iOS Parse Inner Json

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);
}];

Resources