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]);
}
Related
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"]);
}
}
}];
I just need to know proper method to parse the JSON string.
Here is my sample JSON response:
[
{
"my_response": [
{
"name": "XXX",
"Area": "XXX",
"Num": 123
}
]
},
{
"other_response": [
{
"message": "Hello",
"status": "Success",
"flag_value": "1"
}
]
}
]
I want to parse flag_value in a String
I tried this method
NSString *str1 = [json valueForKeyPath:#"other_response. flag_value"];
NSLog(#"str %#",str1);
And my output is some what like this
str (
"<null>",
(
1
)
)
But I want my output to be a string like this:
1
[{"my_response":[{"name":"XXX","Area":"XXX","Num":123}]},{"other_response":[{"message":"Hello","status":"Success","flag_value":"1"}]}]
actually your Json response Start in Array so follow this step
Step-1
NSArray *jsonDict = [NSJSONSerialization JSONObjectWithData:yourData options:Kniloptions error:nil];
Step-2
in here you are get 2 Dictionaries
NSString *FlagStr;
for (NSMutableDictionary *temp in jsonDict)
{
NSArray *secondOption=[temp objectForKey:#"other_response"];
for (NSMutableDictionary *second in secondOption)
{
FlagStr=[second objectForKey:#"flag_value"];
}
}
Choice no-2
I am not try this but May be it work for you , once check
Step-1
NSArray *jsonDict = [[[NSJSONSerialization JSONObjectWithData:yourData options:Kniloptions error:nil]objectAtIndex:1] objectForKey:#"other_response"];
Step-2
NSString *FlagStr;
for (NSMutableDictionary *second in secondOption)
{
FlagStr=[temp objectForKey:#"flag_value"];
}
Choice no-3
you can directly fetch the string value I am not try this but May be it work for you , once check
NSString *flage = [[[NSJSONSerialization JSONObjectWithData:yourData options:Kniloptions error:nil]objectAtIndex:1] objectForKey:#"other_response"]objectAtIndex:0] objectForKey:#"flag_value"];
First of all, I think your JSON would be better formatted like the following:
{
"my_response": {
"name": "XXX",
"area": "XXX",
"num": "XXX"
},
"other_response": {
"message": "Hello",
"status": "success",
"flag_value": "1"
}
}
Then you can use the following code to access your data:
NSString *jsonString = #"{\"my_response\": {\"name\": \"XXX\",\"area\": \"XXX\",\"num\": \"XXX\"},\"other_response\": {\"message\": \"Hello\",\"status\": \"success\",\"flag_value\": \"1\"}}";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
NSLog(#"str: %#", [jsonDict valueForKeyPath:#"other_response.flag_value"]);
Format your Json array like this way.
{
"my_response": {"name": "XXX","area": "XXX","num": "XXX"
},
"other_response": {"message": "Hello","status": "success","flag_value": "1"
}
}
**Step : 2**
Use AFNetworking for HTTP Client
- (void)yourMethod{
NSString *urlString = [NSString stringWithFormat:#"%#", your_service_url];
NSURL *url = [NSURL URLWithString:urlString];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:#"text/html"]];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
your_parameters_list,
nil];
NSMutableURLRequest *jsonRequest = [httpClient requestWithMethod:#"POST"
path:urlString
parameters:params];
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:jsonRequest success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#" Success %#", JSON);
NSDictionary *jsonDictionary1 = [JSON valueForKey:#"my_response"];
NSDictionary *jsonDictionary2 = [JSON valueForKey:#"other_response"];
NSString* name = [jsonDictionary1 valueForKey:#“name”];
NSString* area = [jsonDictionary1 valueForKey:#"name"];
NSString* num = [jsonDictionary1 valueForKey:#"num"];
} failure: ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Fail %#", [error userInfo]);
NSLog(#“Error %#", [error localizedRecoverySuggestion]);
}];
[operation start];
}
As accepted above brother Anbu.Karthick answer.But I want to give answer for this
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:yourResponseData options: NSJSONReadingMutableContainers error: &err];
for (int i =0; i<[jsonArray count]; i++)
{
NSMutableDictionary *dict = [[jsonArray objectAtIndex:i] mutableCopy];
NSString *strFlag = [NSString stringWithFormat:#"%#",[[[dict objectForKey:#"other_response"] objectAtIndex:0] valueForKey:#"flag_value"]];
NSLog(#"The strFlag is-%#",strFlag);
}
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);
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 just get started with Ios programming, and i have to parse a nested Json file and extract the items and lables, the problem is i have to display the list of the items on a tableview and refresh my tableview everytime i click on a row of my table view:
i did display the first list of my items but i'm trying to display my nested items and display them on my "new" tableview:
here are a simple of my JSON code and my objective-c code:
"results": {
"items": [
{
"id": "0100",
"label": "Actualités",
"cover": "http://XXXX_01.jpg",
"coverFrom": "XXX-03",
"coverTo": "2031-CCC18",
"coverOrder": 1,
"items": [
{
"id": "0101",
"label": "Actualité / Infos",
"cover": "http://XXXX.jpg",
"coverFrom": "2014XXX-24",
"coverTo": "2031-XXXX18",
"coverOrder": 1,
"items": [
]
},
and my RootViewContoller contain this code of the function connectionDidFinishiongLoading**
// we will follow the format of our nested JSON
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:dataRequest options:0 error:nil];
NSDictionary *results = [allDataDictionary objectForKey:#"results"];
NSArray *arrayOfItems = [results objectForKey:#"items"];
for (NSDictionary *diction in arrayOfItems) {
//NSArray *ide = [diction objectForKey:#"id"];
NSString *label = [diction objectForKey:#"label"];
// add new object founded
[array addObject:label];
}
// reload my tableview
[[self tableView]reloadData];
// myParsingResults = [NSJSONSerialization JSONObjectWithData:dataRequest options:nil error:nil];
[[self tableView]reloadData];
If I understood correctly, try something like that:
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:dataRequest options:0 error:nil];
NSDictionary *results = [allDataDictionary objectForKey:#"results"];
NSArray *array = [results objectForKey:#"items"];
NSMutableArray *arrayLabels = [[NSMutableArray alloc] init];
NSDictionnary *dicoTemp = [array objectAtIndex:0];
while([dicoTemp objectForKey:#"items"])
{
arrayLabels addObject:[[dicoTemp objectForKey:#"items"] objectForKey:#"label"];
NSArray *arrayTemp = [dicoTemp objectForKey:#"items"];
dicoTemp = [arrayTemp objectAtIndex:0]; //I don't know how you JSON ends, you may have to check if [arrayTemp count] > 0. I presumed that at the end, there was no object for key "items"
}
[[self tableView] reloadData];
That a weird nested JSON response, in my opinion.
Try this one...
NSError *error = nil;
NSURL *Url = [[NSURL alloc] initWithString:#"Your URL"];
jsonData = [NSData dataWithContentsOfURL:Url options:NSDataReadingUncached error:&error];
if(jsonData==Nil){
UIAlertView * alert=[[UIAlertView alloc]initWithTitle:#"Error" message:#"Please check your internet connection" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:#"ok", nil];
[alert show];
}
else{
NSDictionary *dataDictionary =[[NSDictionary alloc]init];
dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
[array addObject:[[[dataDictionary objectForKey:#"results"] valueForKey:#"items"] valueForKey:#"label"]];
}
and reloads your tableview.