Getting error while converting Json data to Object in iOS - ios

I am using an API to convert Json Data into Object data,
please visit the API I am using
Please Visit the API page which I am using
Here is the snap of my code with highlighted issues
Issues
and here is the raw code
-(void) retrieveData{
NSURL * url = [NSURLURLWithString:getDataUrl];
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:nil];
NSLog(#"JsonArray %#", jsonArray);
//setup yougaArray
yougaArray = [[NSMutableArray alloc] init];
//Loop through our jsonArray
for (int i = 0; i<jsonArray.count; i++)
{
NSString * yId = [[[[jsonArray objectAtIndex:i]objectForKey:#"data"]objectAtIndex:#"categories"]objectForKey:#"id"];
// NSString * yId = [[jsonArray objectAtIndex:i]objectForKey:#"id"];
NSString * yName = [[[[jsonArray objectAtIndex:i]objectForKey:#"data"]objectAtIndex:#"categories"]objectForKey:#"name"];
NSString * yDescription = [[[[jsonArray objectAtIndex:i]objectForKey:#"data"]objectAtIndex:#"categories"]objectForKey:#"description"];
NSString * yImage = [[[[jsonArray objectAtIndex:i]objectForKey:#"data"]objectAtIndex:#"categories"]objectForKey:#"image"];
//Add the city object to our citiesArray
[yougaArray addObject:[[Youga alloc]initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
}
[self.tableView reloadData];
}

Thanks #Lame, I followed your code, as it was giving me 6 to 8 errors, but I understand your code & configured error in that now here is the complete solution which works according to my requirements or (perfect answer according to my asked question)
-(void) retrieveData{
NSURL * url = [NSURL URLWithString:getDataUrl];
NSData * data = [NSData dataWithContentsOfURL:url];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSDictionary *dataJSON = [jsonDict objectForKey:#"data"];
NSArray *allCategoriesJSON = [dataJSON objectForKey:#"categories"];
yougaArray = [[NSMutableArray alloc] init];
for (int i = 0; i < allCategoriesJSON.count; i ++)
{
NSDictionary *aCategoryJSON = [allCategoriesJSON objectAtIndex:i];
NSString *yId = [aCategoryJSON objectForKey:#"id"];
NSString *yName = [aCategoryJSON objectForKey:#"name"];
NSString *yDescription = [aCategoryJSON objectForKey:#"description"];
NSString *yImage = [aCategoryJSON objectForKey:#"image"];
[yougaArray addObject:[[Youga alloc] initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
}
[self.tableView reloadData];

According to your JSON response its a Dictionary type object not an array so your code should be like this,
NSMutableDictionary *dictData = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:nil];
NSLog(#"JsonArray %#", dictData);
NSArray *jsonArray=[[dictData objectForKey:#"data"] objectForKey:#"categories"];
//setup yougaArray
yougaArray = [[NSMutableArray alloc] init];
for (int i = 0; i<jsonArray.count; i++)
{
NSString * yId = [[jsonArray objectAtIndex:i] objectForKey:#"id"];
// NSString * yId = [[jsonArray objectAtIndex:i]objectForKey:#"id"];
NSString * yName = [[jsonArray objectAtIndex:i] objectForKey:#"name"];
NSString * yDescription = [[jsonArray objectAtIndex:i] objectForKey:#"description"];
NSString * yImage = [[jsonArray objectAtIndex:i] objectForKey:#"image"];
//Add the city object to our citiesArray
[yougaArray addObject:[[Youga alloc]initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
}
[self.tableView reloadData];
Hope it works for you. Let me know!!
Happy coding. :)

You JSON seems like this :
{
"meta": {
"status": "200",
"msg": "OK"
},
"data": {
"total_pages": 0,
"total_categories": 2,
"current_page": 1,
"next_page": 0,
"categories": [{
"id": "2",
"name": "Articles",
"description": "Yoga Articles",
"image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
}, {
"id": "1",
"name": "Poses",
"description": "Yoga Poses",
"image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
}]
}
}
now replace your existing code with the code below:
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:nil];
NSLog(#"JsonArray %#", jsonArray);
//setup yougaArray
yougaArray = [[NSMutableArray alloc] init];
//Loop through our jsonArray
NSArray *dataArray = [[jsonArray objectForKey#"data"] objectForKey:#"categories"];
for (int i = 0; i < dataArray.count; i++) {
NSString * yId = [[dataArray objectAtIndex:i] objectForKey:#"id"];
NSString * yName = [[dataArray objectAtIndex:i] objectForKey:#"name"];
NSString * yDescription = [[dataArray objectAtIndex:i] objectForKey:#"description"];
NSString * yImage = [[dataArray objectAtIndex:i] objectForKey:#"image"];
//Add the city object to our citiesArray
[yougaArray addObject:[[Youga alloc]initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
}
[self.tableView reloadData];
Let me know if the solution works for you, also if anything comes up.

This is the JSON:
{
"meta": {
"status": "200",
"msg": "OK"
},
"data": {
"total_pages": 0,
"total_categories": 2,
"current_page": 1,
"next_page": 0,
"categories": [{
"id": "2",
"name": "Articles",
"description": "Yoga Articles",
"image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
}, {
"id": "1",
"name": "Poses",
"description": "Yoga Poses",
"image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
}]
}
}
Your JSON is a NSDictionary at top level! Not a NSArray!
Also, avoid doing all objectForKey:/objectAtIndex: in the same line/instruction, it's harder to read, but also harder to debug, especially when you don't know what you are doing.
Also, when there is an error parameter, use it, don't put nil.
So:
NSError *errorJSON = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorJSON];
if (errorJSON)
{
NSLog(#"ErrorJSON: %#", errorJSON);
return;
}
NSDictionary *dataJSON = [jsonDict objectForKey:#"data"];
NSArray *allCategoriesJSON = [dataJSON objectForKey:#"categories"];
for (NSUIInteger i = 0; i < allCategoriesJSON.count; i ++)
{
NSDictionary *aCategoryJSON = [allCategoriesJSON objectAtIndex:i];
NSString yID = [aCategoryJSON objectForKey:#"id"];
NSString yName = [aCategoryJSON objectForKey:#"name"];
NSString yDescription = [aCategoryJSON objectForKey:#"description"];
NSString yImage = [aCategoryJSON objectForKey:#"image"];
[yougaArray addObject:[[Youga alloc] initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
}

Related

JSON String with Arrays iOS

My APP gets a JSON string from a api call JSON string has objects and a array in it. This is what i have done so far but i couldn't get the values from it . advice me please and I'm new to iOS .This is my JSON String :
{
"Id":"0d95a9f6-c763-4a31-ac6c-e22be9832c83",
"Name":"john",
"ProjectName":"project1",
"StartDate":"\/Date(1447200000000)\/",
"Documents":
[{
"Id":"2222a","Name":"book1","ContentType":"application/pdf"
},
{
"Id":"3718e","Name":"Toolbox","ContentType":"application/fillform"
}]
}
Code
NSString *URLString = [NSString stringWithFormat:#"http://mysite/API/Assignments?"];
NSURL *url = [NSURL URLWithString:URLString];
NSData *data=[NSData dataWithContentsOfURL:url];
json=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
assignArray=[[NSMutableArray alloc]init];
for (int i=0; i<json.count; i++) {
NSString *aID=[[json objectAtIndex:i]objectForKey:#"Id"];
NSString *uName=[[json objectAtIndex:i]objectForKey:#"Name"];
NSString *pName=[[json objectAtIndex:i]objectForKey:#"ProjectName"];
//[self initwithUserID:uID userName:uName proName:pName];
// [self retrieveAssignmentDetails:aID];
AssignmentsJson *assignment=[[AssignmentsJson alloc]initwithassignID:aID userName:uName proName:pName];
[assignArray addObject:assignment];
your json is not array so parse like following
NSString *aID = json[#"Id"];
NSString *uName = json[#"Name"];
NSString *pName = json[#"ProjectName"];
NSString *startDate = json[#"StartDate"];
NSArray *documents = json[#"Documents"];
for (NSDictionary *item in documents) {
NSString *itemID = item[#"Id"];
NSString *itemName = item[#"Name"];
NSString *itemContentType = item[#"ContentType"];
}
Your Json Object is NSDictionary. so you can directly get data using valueForKey
NSDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSString *aID = json[#"Id"];
NSString *uName = json[#"Name"];
NSString *pName = json[#"ProjectName"];
for Id,Name and ContentType is inside your array object within your NSDictionary object.
so you can get those values accessing array index.
NSArray *arr = json[#"Documents"];
for (int i=0; i<arr.count; i++) {
NSString *aID=[[arr objectAtIndex:i]objectForKey:#"Id"];
NSString *uName=[[arr objectAtIndex:i]objectForKey:#"Name"];
NSString *cType=[[arr objectAtIndex:i]objectForKey:#"ContentType"];
}
You should learn NSArray and NSDictionary Structure first. it will help you in future. Hope this will help you.
you can do it by following way.
Your Json is in NSDictionary format.
NSData * data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://mysite/API/Assignments?"]];
NSDictionary * dicResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if(dicResponse){
NSString * strID = [dicResponse valueForKey:#"Id"];
NSString * strName = [dicResponse valueForKey:#"Name"];
NSString * strProjectName = [dicResponse valueForKey:#"ProjectName"];
NSString * strDate = [dicResponse valueForKey:#"StartDate"];
NSArray * arrDocuments = [NSArray arrayWithArray:[dicResponse valueForKey:#"Documents"]];
for (int i=0; i< arrDocuments.count; i++) {
NSString * ID=[[arrDocuments objectAtIndex:i]valueForKey:#"Id"];
NSString * Name=[[arrDocuments objectAtIndex:i]valueForKey:#"Name"];
NSString * Type=[[arrDocuments objectAtIndex:i]valueForKey:#"ContentType"];
}
}

JSON extract Facebook Graph API iOS xcode

I'm in need take the data that passes facebook me with the scores of the players, but I can not return the values that are within the braces in xcode.
Example:
{
"data": [
{
"user": {
"id": "927806543903674",
"name": "Renata Gabi"
},
"score": 333,
"application": {
"name": "Player 2",
"namespace": "quemsoueubiblico",
"id": "303489829840143"
}
},
{
"user": {
"id": "964974026864922",
"name": "Player 1"
},
"score": 230,
"application": {
"name": "My Game",
"namespace": "quemsoueubiblico",
"id": "303489829840143"
}
}
]
}
In android I use this
...
jgame = jObject.getJSONArray("data");
...
score = jgame.getString("score");
name = jgame.getJSONObject("user").getString("name");
photo_id = jgame.getJSONObject("user").getString("id");
for ios in xcode, I was trying this, but is not working
myObject = [[NSMutableArray alloc] init];
NSData *jsonSource = [[NSData alloc] initWithContentsOfURL:
[NSURL URLWithString:#"http://www.escoladepsicanalisekoinonia.com/teste/index.html"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:
jsonSource options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dataDict in jsonObjects) {
NSString *score_data = [dataDict objectForKey:#"score"];
NSString *name_data = [dataDict objectForKey:#"name"];
NSString *id_data = [dataDict objectForKey:#"id"];
NSLog(#.........);
dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
score_data, score,
name_data, name,
id_data, id,
nil];
[myObject addObject:dictionary];
}
I am not able to adjust the "data" facebook graph, and get the subclasses
The data item in your JSON sample is an array, but you're not taking this into account in your code. Try this:
myObject = [[NSMutableArray alloc] init];
NSData *jsonSource = [[NSData alloc] initWithContentsOfURL:
[NSURL URLWithString:#"http://www.escoladepsicanalisekoinonia.com/teste/index.html"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:
jsonSource options:NSJSONReadingMutableContainers error:nil];
NSArray *data = [jsonObjects objectForKey:#"data"];
for (NSDictionary *dataDict in data) {
NSString *score_data = [dataDict objectForKey:#"score"];
NSDictionary *user_data = [dataDict objectForKey:#"user"];
NSString *name_data = [user_data objectForKey:#"name"];
NSString *id_data = [user_data objectForKey:#"id"];
NSLog(#.........);
dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
score_data, score,
name_data, name,
id_data, id,
nil];
[myObject addObject:dictionary];
}

how to parse json in ios using web url [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
hi i getting json from an external source and parsing it in ios. my code is below
Note = json and cats variables are NSArray;
NSURL * url = [NSURL URLWithString:#"http://myurl.json"];
NSData * data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
cats = [[NSMutableArray alloc] init];
for (int i=0; i < json.count; i++) {
NSString * CatId = [[json objectAtIndex:i] objectForKey:#"id"];
NSString * CatName = [[json objectAtIndex:i] objectForKey:#"name"];
NSString * CatIcon = [[json objectAtIndex:i] objectForKey:#"icon"];
categories * cat = [[categories alloc] initWithCId:CatId andCName:CatName andCIcon:CatIcon];
[cats addObject:cat];
and json is here
{"categories":[{"id":1,"name":"Healthcare","icon":"/icons/images/65/original_56.png?1386745569"},{"id":10,"name":"Mall","icon":"/icons/images/60/original_51.png?1386745369"},{"id":11,"name":"Taupheq","icon":"/icons/images/23/original_14.png?1386744595"},{"id":12,"name":"Hotel","icon":"/icons/images/27/original_18.png?1386744659"},{"id":13,"name":"SPA","icon":"/icons/images/48/original_39.png?1386745093"},{"id":14,"name":"ATM","icon":"/icons/images/22/original_13.png?1386744578"},{"id":15,"name":"Travel","icon":"/icons/images/12/original_3.png?1386744393"},{"id":16,"name":"Game zone","icon":"/icons/images/68/original_59.png?1386745626"},{"id":17,"name":"Academic","icon":"/icons/images/10/original_1.png?1386744264"},{"id":18,"name":"Textile","icon":"/icons/images/46/original_37.png?1386745050"}]}
Try this:
NSURL * url = [NSURL URLWithString:#"http://myurl.json"];
NSData * data = [NSData dataWithContentsOfURL:url];
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray *catsArray = [NSArray arrayWithArray:[json objectForKey:#"categories"]];
cats = [[NSMutableArray alloc] init];
for (int i = 0; i < catsArray.count; i++) {
NSString * CatId = [[catsArray objectAtIndex:i] objectForKey:#"id"];
NSString * CatName = [[catsArray objectAtIndex:i] objectForKey:#"name"];
NSString * CatIcon = [[catsArray objectAtIndex:i] objectForKey:#"icon"];
categories * cat = [[categories alloc] initWithCId:CatId andCName:CatName andCIcon:CatIcon];
[cats addObject:cat];
}
try this:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
json = [dict objectForKey:#"categories"];
When you are trying this:
NSString * CatId = [[json objectAtIndex:i] objectForKey:#"id"];
It translates into: Array -> Dictionary -> String
But you can see you dont want this.
You want: Dictionary -> Array -> Dictionary ->String
In Code:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray *array = [dict objectForKey:#"categories"];
NSString * CatId = [[array objectAtIndex:0] objectForKey:#"id"];
try this . . .
NSURL * url = [NSURL URLWithString:#"http://myurl.json"];
NSData * data = [NSData dataWithContentsOfURL:url];
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray * cat = [json objectForKey:#"categories"];
for(NSDictionary * tempdict in cat)
{
NSString * CatId = [NSString stringWithFormat:#"%#",[tempdict objectForKey:#"id"]];
NSString * CatName = [tempdict objectForKey:#"name"];
NSString * CatIcon = [tempdict objectForKey:#"icon"];
categories * cat = [[categories alloc] initWithCId:CatId andCName:CatName andCIcon:CatIcon];
}
THis should work : Consider the Json as NSMutableArray and then easily you ail get the array of the object one by one :
NSMutableArray *userDetails = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:nil];
NSLog(#"User Det %#", userDetails);
if (userDetails == nil || [userDetails count] == 0) {
} else {
// 3. iterate the array; each element is a dictionary...
for (NSDictionary *lesson in userDetails)
{
NSString * CatId = [[catsArray objectAtIndex:i] objectForKey:#"id"];
NSString * CatName = [[catsArray objectAtIndex:i] objectForKey:#"name"];
NSString * CatIcon = [[catsArray objectAtIndex:i] objectForKey:#"icon"];
categories * cat = [[categories alloc] initWithCId:CatId andCName:CatName andCIcon:CatIcon];
[cats addObject:cat];
}
}
NSURL * url = [NSURL URLWithString:#"http://myurl.json"];
NSData * data = [NSData dataWithContentsOfURL:url];
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray *myArray = [jsonData objectForKey:#"categories"];
cats = [[NSMutableArray alloc] init];
for (NSDictionary *temp in myArray) {
NSString * CatId = [NSString stringWithFormat:#"%d",[temp objectForKey:#"id"]];
NSString * CatName = [temp objectForKey:#"name"];
NSString * CatIcon = [temp objectForKey:#"icon"];
categories * cat = [[categories alloc] initWithCId:CatId andCName:CatName andCIcon:CatIcon];
[cats addObject:cat];
}

How can I parse json in iOS

I have the following JSON!
This JSON wrote my bear drunk vodka :D
{
"Label": [ 1, 2, 3, 4, 5 ],
"ViewId": 1
}
code:
NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
for (int i=0; i < json.count; i++)
{
NSString * FRid = [[json objectAtIndex:i] objectForKey:#"ViewId"]; //it's work
NSString * FRName = [[json objectAtIndex:i] objectForKey:#"Label"]; //it's don't work Out of scope
How I can get data from "Label" to NSString?
Try:
NSString * FRid = [[json objectAtIndex:i] objectForKey:#"ViewId"];
NSArray * FRName = [[json objectAtIndex:i] objectForKey:#"Label"];
*Label Key contains an array, not a string.
And after this you can convert the array to string by following,
NSString *FRNameString = [FRName componentsJoinedByString:#", "];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *label = [dict objectForKey:#"Label"];
//convert to string
NSString *final = [[NSString alloc]init];
for (NSString * string in label){
final = [NSString stringWithFormat:#"%#%#", final, string];
}
NSLog(#"%#",final);
This is very close pseudocode
I wrote this on my phone, so i can't format as code.

Parsing a JSON file

How can I parse a file of this kind:
{"group":"1"}{"group":"2"}{"group":"3"}
Usually I parse in this way:
NSString *fileContent = [[NSString alloc] initWithContentsOfFile:reloadPath];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];
// getting the data from inside of "menu"
//NSString *message = (NSString *) [data objectForKey:#"message"];
//NSString *name = (NSString *) [data objectForKey:#"name"];
NSArray *messagearray = [data objectForKey:#"message"];
NSArray *namearray = [data objectForKey:#"name"];
NSDictionary* Dictionary = [NSDictionary dictionaryWithObjects:messagearray forKeys:namearray];
...objects of this king...
{"message":["Besth"],"name":["thgh"]}
...but in the type I want to parse, which is the key and object??
By the way I want to retrieve a list like this: 1, 2, 3, ...
This is not valid JSON. You can validate for example at: http://jsonlint.com
You could rewrite it as valid JSON like so:
{
"some_groups": [
{
"group": "1"
},
{
"group": "2"
},
{
"group": "3"
}
]
}
Then you could extract the data by doing something like this:
NSArray *groups = [data objectForKey:#"some_groups"];
for (NSDictionary *group in groups) {
NSLog(#"group number: %#", [group valueForKey:#"group"]);
}

Resources