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);
}
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"]);
}
}
}];
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'trying to get some random JSON from http://schematic-ipsum.herokuapp.com/ but I'm getting a response code 400.
Here is the code I'm using
+ (NSArray *)postData:(NSDictionary *)arguments toServer:(NSString *)urlString
{
NSArray *dataToReturn;
// if urlString is nil, we default it to our server
if(!urlString) urlString = JSON_SERVER;
// of course we need to turn the string into a valid array
NSURL *url = [NSURL URLWithString:urlString];
/*
prepare the post
*/
// we need to catch possible errors
NSError *error;
// turn our arguments into NSData
NSData *postData = [NSJSONSerialization dataWithJSONObject:arguments options:0 error:&error];
// we need the post' length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
// create the url request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
// here we'll check the server response
NSHTTPURLResponse *response = nil;
// here's our data from the server
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
// all good, let's see what we've got
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
// parse the response into a friendly format
dataToReturn = [[NSArray alloc] initWithArray:[self returnJSONFromData:urlData]];
} else {
// somethin went wrong
NSLog(#"Response code: %ld", (long)[response statusCode]);
// check if it's our fault
if (error) {
NSLog(#"Server error: %#", [error localizedDescription]);
}
}
// return our formatted array or nil
return dataToReturn;
}
+ (NSArray *)returnJSONFromData:(NSData *)urlData
{
NSArray *dataToReturn;
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: urlData options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#", [e localizedDescription]);
dataToReturn = #[e];
} else {
dataToReturn = [[NSArray alloc] initWithArray:jsonArray];
NSLog(#"data from json: %#", dataToReturn);
}
return dataToReturn;
}
and I'm calling it like this, using a demo JSON from their website:
NSDictionary *post = #{ #"type": #"object", #"properties": #{ #"id": #{ #"type": #"string", #"ipsum": #"id" }, #"name": #{ #"type": #"string", #"ipsum": #"name" }, #"email": #{ #"type": #"string", #"format": #"email" } }};
[RetrieveDataFromServer postData:post toServer:#"http://schematic-ipsum.herokuapp.com/"];
You need to respect the syntax of "Form Data" that the server takes. To obtain this, you can use Google Chrome "Inspect Element", choose "Network" tab then do a request and you'll see this:
Look at "Form Data" section and you'll find out your problem, it's because you didn't pass the right structure to server so that the server doesn't understand.
I took the defaults parameters of server which is:
{
"type": "object",
"properties": {
"id": {
"type": "string",
"ipsum": "id"
},
"name": {
"type": "string",
"ipsum": "name"
},
"email": {
"type": "string",
"format": "email"
},
"bio": {
"type": "string",
"ipsum": "sentence"
},
"age": {
"type": "integer"
},
"avatar": {
"type": "string",
"ipsum": "small image"
}
}
}
So the data must be structured like this:
type:object
properties[id][type]:string
properties[id][ipsum]:id
properties[name][type]:string
properties[name][ipsum]:name
properties[email][type]:string
properties[email][format]:email
properties[bio][type]:string
properties[bio][ipsum]:sentence
properties[age][type]:integer
properties[avatar][type]:string
properties[avatar][ipsum]:small image
And don't forget to encode with percentage before sending it to server or you will fail again.
I tried to implement a method that take your dictionary and return the formatted form data, it works fine for this case but I'm not sure in a more general context. I'll post it here for you as a reference, it's really a mess, sorry for that but I don't have enough time for commenting.
- (NSString *)formatFormData:(NSDictionary *)dictionary
{
NSMutableArray *arrayPrefix = [NSMutableArray array];
NSMutableArray *arrayResult = [NSMutableArray array];
[self structureString:dictionary arrayPrefix:arrayPrefix arrayResult:arrayResult];
return [arrayResult componentsJoinedByString:#"&"];;
}
- (void)structureString:(NSDictionary *)dictionay arrayPrefix:(NSMutableArray *)arrayPrefix arrayResult:(NSMutableArray *)arrayResult
{
for(NSString *key in dictionay.allKeys)
{
NSObject *obj = [dictionay objectForKey:key];
if([obj isKindOfClass:[NSDictionary class]])
{
[arrayPrefix addObject:key];
[self structureString:(NSDictionary *)obj arrayPrefix:arrayPrefix arrayResult:arrayResult];
}
else
{
NSMutableString *string = [[NSMutableString alloc] initWithString:#""];
for(int i = 0; i < arrayPrefix.count; i++)
{
NSString *eachPrefix = arrayPrefix[i];
if(i == 0)
{
[string appendString:eachPrefix];
}
else
{
[string appendString:[NSString stringWithFormat:#"[%#]", eachPrefix]];
}
}
if(arrayResult.count == 0)
{
[string appendString:[NSString stringWithFormat:#"%#=%#", key, obj]];
}
else
{
[string appendString:[NSString stringWithFormat:#"[%#]=%#", key, obj]];
}
[arrayResult addObject:string];
}
}
}
And in your current method, add these lines:
- (NSArray *)postData:(NSDictionary *)arguments toServer:(NSString *)urlString
{
// omitted
// turn our arguments into NSData
NSData *postData = [NSJSONSerialization dataWithJSONObject:arguments options:0 error:&error];
NSString *stringTemp = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
stringTemp = [self formatFormData:arguments];
// encode form date before sending to server
stringTemp = [stringTemp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
postData = [stringTemp dataUsingEncoding:NSUTF8StringEncoding];
// omitted
}
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]);
}
I am Using URL For Access JSON file
I get this From Following code
NSData* data=[jsonString dataUsingEncoding: [NSString defaultCStringEncoding] ];
NSError *error; //where jsonString is string of URL
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (jsonDictionary==nil) {
NSLog(#"Error::Loading");
}else
{
NSArray *array = [jsonDictionary objectForKey:#"categories"];
for (int i=0; i<[array count]; i++) {
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setValue:[[array objectAtIndex:i] valueForKey:#"cat_id"] forKey:#"cat_id"];
[dic setValue:[[array objectAtIndex:i] valueForKey:#"cat_name"] forKey:#"cat_name"];
[dic setValue:[[array objectAtIndex:i] valueForKey:#"cat_image"] forKey:#"cat_image"];
[dic setValue:[[array objectAtIndex:i] valueForKey:#"cat_list"] forKey:#"cat_list"];
[newsArray addObject:dic];
[categoryArry addObject:[dic valueForKey:#"cat_name"]];
[categoryId addObject:[dic valueForKey:#"cat_id"]];
[categoryImage addObject:[dic valueForKey:#"cat_image"]];
[categoryList addObject:[dic valueForKey:#"cat_list"]];
[dic release];
}
}
and get json Structure Like This
{
"categories": [
{
"cat_id": "15",
"cat_name": "Shop",
"cat_image": null,
"cat_list": [
{
"sub_cat_name": "New Arrivals",
"Cat_Data": [
{
"prod_name": "Generals Coat Biege",
"prod_price": "215.0000",
"prod_image": "honey_beau_lookbook_winter13_febmarch-24.jpg"
}
]
}
]
}
]
}
categoryArry contain only ine value "Shop"
but i want to access "sub_cat_name" in categoryArry and skip the Shop Level....
In short I want to store "sub_cat_name" in to categoryArry.
Surely you just need to do:
NSArray *catlist = [dic valueForKey:#"cat_list"]
NSDictionary *firstcat = [catlist objectAtIndex:0];
NSString *subcatname = [firstcat valueForKey:#"sub_cat_name"];
This assumes of course that you have at least one item in the cat_list array.
I'm using 3rd party library called AFNetworking to make JSON requests and parse the response.
Here's an example:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:#"http://yoursite.com"];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"blah/path"
parameters:#{#"jsonKey":#"jsonValue"}];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *res, id json) {
// Use the json here
json[#"categories"][0][#"cat_list"];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id json) {
//Handle Errors
}];
[operation start];
At your code replace:
[categoryArry addObject:[dic valueForKey:#"cat_name"]];
by
[categoryArry addObject:[[dic valueForKey:#"cat_list"][0]] valueForKey:#"sub_cat_name"];
Anyway you could use the jsonDictionary directly instead of creating another dict.