I am developing simple app that gets json data and stores into different variables
here is my code that gets json data
if ([method isEqualToString:#"getmobiledata"]){
defaultDict = [[NSMutableDictionary alloc]init];
[defaultDict addEntriesFromDictionary:[NSJSONSerialization JSONObjectWithData:[data dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]];
mobile = [defaultDict objectForKey:#"data"];
}
here is my son data:
{
data = (
{
id = 1;
package = 819MB;
rate = "$1";
type = Somnet;
},
{
id = 2;
package = "1,638MB";
rate = "$2";
type = Somnet;
},
);
}
here is paring json into nstring :
for(NSDictionary *getData in mobile){
NSString *idno = [getData objectForKey : #"id"];
NSString *package = [getData objectForKey :#"package"];
NSString *rate = [getData objectForKey :#"rate"];
NSString *type = [getData objectForKey :#"type"];
}
please help me how to solve this
The data model will collide with the same name as the system property ID, and it will collide and crash.
You can use a new ID like this:
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
if([key isEqualToString:#"id"])
self.NewId = value;
}
This question already has answers here:
Cocoa-Touch - How parse local Json file
(5 answers)
Closed 7 years ago.
When i parse one JSON i got following result inside my NSArray
(
{
category = Allergies;
group = Allergies;
name = "Food Allergies";
option = "";
subGroup = "";
type = VARCHAR;
},
{
category = Allergies;
group = Allergies;
name = "Drug Allergies";
option = "";
subGroup = "";
type = VARCHAR;
},
{
category = Allergies;
group = "";
name = "Blood Group";
option = "[{\"id\":1,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"A+\"},{\"id\":2,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"A-\"},{\"id\":3,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"B+\"},{\"id\":4,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"B-\"},{\"id\":5,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"O+\"},{\"id\":6,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"O-\"},{\"id\":7,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"AB+\"},{\"id\":8,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"AB-\"}]";
subGroup = "";
type = SINGLESELECT;
}
)
Now when i tried to take value for key "option"
[array valueForKey:#"option"]objectAtIndex:indexPath.row];
i got following result
[{"id":1,"isDefault":false,"additionalOption":false,"optionName":"A+"},{"id":2,"isDefault":false,"additionalOption":false,"optionName":"A-"},{"id":3,"isDefault":false,"additionalOption":false,"optionName":"B+"},{"id":4,"isDefault":false,"additionalOption":false,"optionName":"B-"},{"id":5,"isDefault":false,"additionalOption":false,"optionName":"O+"},{"id":6,"isDefault":false,"additionalOption":false,"optionName":"O-"},{"id":7,"isDefault":false,"additionalOption":false,"optionName":"AB+"},{"id":8,"isDefault":false,"additionalOption":false,"optionName":"AB-"}]
but when tried to access "optionName" like following format
[optionArray valueForKey:#"optionName"];
then i got this error
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFConstantString 0x10d8638a0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key optionName.'
Please help me to fix this..
Assuming you are using ios 5 or higher, JSON serialization is built in:
NSArray *json = [NSJSONSerialization
JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding]
options:kNilOptions
error:&error];
Prior to ios5, you can use SBJSON to achieve the same:
NSArray *jsonObjects = [jsonParser objectWithString:string error:&error];
Use this method
- (NSArray *)convertStringToDictionary:(NSString *)str{
NSError *jsonError;
NSData *objectData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSArray *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError];
return json;
}
And call like this
NSArray *arr = [self convertStringToDictionary:#"[{\"id\":1,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"A+\"},{\"id\":2,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"A-\"},{\"id\":3,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"B+\"},{\"id\":4,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"B-\"},{\"id\":5,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"O+\"},{\"id\":6,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"O-\"},{\"id\":7,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"AB+\"},{\"id\":8,\"isDefault\":false,\"additionalOption\":false,\"optionName\":\"AB-\"}]"];
NSLog(#"Option Name ----> %#",[[arr objectAtIndex:0] valueForKey:#"optionName"]);
OUTPUT
Option Name ----> A+
Try using below got to convert to array
NSArray *tmpDayArray=[[NSArray alloc]init];
NSError *error;
NSData *dictData = [NSJSONSerialization dataWithJSONObject:tmpDayArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *open_days = [[NSString alloc] initWithData:dictData encoding:NSUTF8StringEncoding];
Try Below code for convert it to NSArray
NSArray * array =[NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:#"%#",#"YOUR STRING"] dataUsingEncoding:NSUTF8StringEncoding]options: NSJSONReadingMutableContainers error:nil];
You have a complex "object graph." It looks like your outer object is an array, and inside that you have dictionaries.
If optionArray is an NSArray then it will give you exactly the error you are reporting if you try to treat it as a dictionary.
Your code:
[array valueForKey:#"option"]objectAtIndex:indexPath.row];
Is doing that (Although you are using KVC, where you should be using array and dictionary methods directly.)
Your code should look like this instead:
NSDictionary* aDict = array[indexPath.row];
NSString *optionString = aDict[#"option];
Without using any third party like SBJson
NSString *optionString = [[array valueForKey:#"option"]objectAtIndex:indexPath.row];
Actually you are getting optionString as json String so you have to parse it and then use like this
NSData *data = [optionString dataUsingEncoding:NSUTF8StringEncoding];
NSArray * optionArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"%#",[optionArray valueForKey:#"optionName"]);
I got json reponse in the following way...i have tried to parse in many ways all went ruin.
dic:
(
{
events = {
id = 1;
name = "Event One";
};
},
{
events = {
id = 2;
name = "Test 2";
};
},
{
events = {
id = 12;
name = "vivek 11";
};
},
)
NSDictionary *jsonDictionaryResponse = [response JSONValue];
NSString *name=[[[jsonDictionaryResponse objectForKey:#"events"]objectAtIndex:0]valueForKey:#"name"];
json response:
Login response :[{"events":{"id":"1","name":" Event
One"}},{"events":{"id":"2","name":"Test
2"}},{"events":{"id":"12","name":"vivek
11"}},{"events":{"id":"13","name":"Baby's Day
out"}},{"events":{"id":"15","name":"Childrens
Day"}},{"events":{"id":"16","name":"event
two"}},{"events":{"id":"17","name":"Test
Creattion"}},{"events":{"id":"29","name":"Susan
Test"}},{"events":{"id":"30","name":"Summer
Holidays"}},{"events":{"id":"38","name":"Event
7"}},{"events":{"id":"69","name":"vivek event for
tests"}},{"events":{"id":"102","name":"chinees food mela"}}]
first transform your response string to NSData. then try this:
NSError *error;
NSArray *jSONArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
for (NSDictionary *dict in jSONArray) {
NSDictionary *event = [dict objectForKey=#"events"];
NSString *name = [event objectForKey:#"name"];
....
}
The easiest way to understand a JSON object in Objective-C is to understand how it breaks things up into Arrays and Dictionaries. Every time you see a "[" think Array. Every time you see a "{" think Dictionary.
An Array can have Dictionary or other Array objects as part of the collection and a Dictionary can have Array or more Dictionary objects which can contain more Arrays or Dictionaries.
If you remember that "[ ]" means Array and "{ }" means Dictionary, you will know JSON in Objective-C.
Check that result coming as JSON. it is not aDictionary check it
here
PLease find the code here
NSArray *jsonArrayResponse = [response JSONValue];
NSDictionary *firstDic = [jsonArrayResponse objectAtIndex:0];
NSDictionary *secondDic = [firstDic objectForKey:#"events"];
NSLog(#"The values in the events dictioanry is %# ",[secondDic allValues]);
NSString *stringNAme = [secondDic objectForKey:#"id"];
I get this JSON from a web service:
{
"Respons": [{
"status": "101",
"uid": "0"
}]
}
I have tried to access the data with the following:
NSError* error;
//Response is a NSArray declared in header file.
self.response = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *test = [[self.response objectAtIndex:0] objectForKey:#"status"]; //[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance
NSString *test = [[self.response objectForKey:#"status"] objectAtIndex:0]; //(null)
But none of them work, if i NSLog the NSArray holding the serialized data, this i what i get:
{
Respons = (
{
status = 105;
uid = 0;
}
);
}
How do i access the data?
Your JSON represents a dictionary, for whom the value associated with the Respons key is an array. And that array has a single object, itself a dictionary. And that dictionary has two keys, status and uid.
So, for example, if you wanted to extract the status, I believe you need:
NSArray *array = [self.response objectForKey:#"Respons"];
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *status = [dictionary objectForKey:#"status"];
Or, in latest versions of the compiler:
NSArray *array = self.response[#"Respons"];
NSDictionary *dictionary = array[0];
NSString *status = dictionary[#"status"];
Or, more concisely:
NSString *status = self.response[#"Respons"][0][#"status"];
Your top level object isn't an array, it's a dictionary. You can easily bypass this and add the contents of that key to your array.
self.response = [[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error] objectForKey:#"Respons"];
I just fetched data but when i try to append it to string from NSData , compiler occurs Exception error .
My code seems like this:
NSDictionary *allDAtaDictionary = [NSJSONSerialization JSONObjectWithData:_webData options:0 error:nil];
NSString *jSonStatus = [allDAtaDictionary objectForKey:#"status"];
if([jSonStatus isEqualToString:#"OK"])
{
NSDictionary *results = [allDAtaDictionary objectForKey:#"user_details"];
NSLog(#"User Details : %#",results);
All things works well until these line just starts:
NSString *userID = [results objectForKey:#"userID"];
The error output is :
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]:
unrecognized selector sent to instance 0x9485a00'
and this is my jSOn output , NSLog(#"User Details : %#",results);
User Details : (
{
userCity = California;
userCountry = "United States";
userDOB = "1988-03-02";
userDetails = "";
userEmail = "xxx#xxx.com";
userFBID = 715296184;
userFullName = "John Mc Grager";
userGender = Male;
userID = 70;
userLastLoginTime = "2013-05-29 10:51:27";
userLatitude = "37.7858";
userLongtitude = "-122.406";
userNickName = warblader;
userPassword = "";
userStatus = 1;
userToken = "";
}
)
Seems like the JSON is an array with one dictionary in it. What you show us here at least.
So
NSArray *results = [allDAtaDictionary objectForKey:#"user_details"];
NSLog(#"User Details : %#",results);
assert(results.count>0);
NSDictionary *user = [results objectAtIndex:0];
NSString *userID = [results objectForKey:#"userID"];
NSLog(#"%#", userID);
First of all you need save use the serialised data into an array.. Then you have to use it accordingly .. in this case
NSArray *allDAtaDictionary = [NSJSONSerialization JSONObjectWithData:_webData options:0 error:nil];
Log the array in index 0 and the see what you are getting. After this you can start parsing the data.
The exception is occuring due to this. Check my answer here to parse JSON How to parse JSON with multiple instance in Object C
Your response probably has An array in it, which result Dictionary is being holding, so you need to use ObjectAtIndex rather calling objectForKey