I am trying to ready a JSON output into an array in iOS. But the array is not being filled at all. Here is the relevant code:
- (void) retrieveData;
{
NSString *getDataURL = #"http://localhost:8888/finalproject/ios/getHouseBills.php";
NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
houseBillsArray = [[NSMutableArray alloc] init];
long test = jsonArray.count;
for(int i = 0; i < jsonArray.count; i++)
{
NSString * hBID = [[jsonArray objectAtIndex:i] objectForKey:#"houseBillID"];
NSString * hID = [[jsonArray objectAtIndex:i] objectForKey:#"houseID"];
NSString * hName = [[jsonArray objectAtIndex:i] objectForKey:#"name"];
NSString * hAmount = [[jsonArray objectAtIndex:i] objectForKey:#"amount"];
NSString * hDate = [[jsonArray objectAtIndex:i] objectForKey:#"date"];
NSString * hAddedBy = [[jsonArray objectAtIndex:i] objectForKey:#"addedBy"];
[houseBillsArray addObject:[[House alloc]initWithHouseBillID:hBID andHouseID: hID andName: hName andAmount: hAmount andDate: hDate andAddedBy: hAddedBy]];
}
[self.tableView reloadData];
[self.refreshControl endRefreshing];
}
Here is an example of the JSON input it will be taking:
[{"houseBillID":"1","houseID":"20","name":"Loo roll","amount":"32453","date":"eqferf","addedBy":"samstone920#googlemail.com"},{"houseBillID":"2","houseID":"20","name":"toothpaste","amount":"3","date":"wefe","addedBy":"44tq"}]
Excuse the fact it is mostly gibberish. But yeah, the array isn't being filled at all. Something tells me its down to character sets, but I'm not sure.
Any help much appreciated.
EDIT: I tried parsing the JSON raw, and that worked fine.
EDIT: The data is being retrieved fine. Just NSLog'ed the data variable.
Related
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"];
}
}
I have the json data were within the first array I main category array with name "Response" within that I have parent category array with name "0" within which I have child category array with name "0" and here is my json format
{"Response":[{"menuname":"Jewellery","menuid":"1","0":[{"catname":"Rings","catid":"1","0":[{"scatname":"Engagement Rings","scatid":"4"},{"scatname":"Wedding Rings","scatid":"5"},{"scatname":"kk","scatid":"35"}]},{"catname":"Pendants","catid":"2","0":[{"scatname":"Office Wear","scatid":"8"}]},{"catname":"Bracelets","catid":"3","0":[{"scatname":"Studded","scatid":"9"}]},{"catname":"Earrings","catid":"6","0":[{"scatname":"Ethnic Jhumkas","scatid":"7"}]},{"catname":"Chain's","catid":"33","0":[]},{"catname":"Jewel","catid":"34","0":[]}]},{"menuname":"Collections","menuid":"2","0":[{"catname":"SOUND OF LOVE","catid":"15","0":[{"scatname":"LOVE BRACELET","scatid":"16"}]},{"catname":"COLORFUL AFFAIR","catid":"17","0":[{"scatname":"Passion ring","scatid":"18"}]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]},{"menuname":"Gold Coin","menuid":"3","0":[{"catname":"SOUND OF LOVE","catid":"15","0":[{"scatname":"LOVE BRACELET","scatid":"16"}]},{"catname":"COLORFUL AFFAIR","catid":"17","0":[{"scatname":"Passion ring","scatid":"18"}]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]},{"menuname":"OFF THE SHELF","menuid":"4","0":[{"catname":"testing from pixel","catid":"13","0":[]},{"catname":"New pixel","catid":"23","0":[]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]}]}
and I want to display in expandable tableview as below
Jewellery
Rings
Engagement Rings
Wedding Rings
kk
Pendants
Ofice Wear
Collections
Sound Of Love
Love bracelet
Colorful Affair
Passion ring
Here is the code I used in viewdidLoad
NSDictionary *pJson;
NSMutableString *postStr = [NSMutableString stringWithString:kURL];
[postStr appendString:[NSString stringWithFormat:#"?tag=%#&id=%#",kCategoryFilter,kPrecious]];
[postStr setString:[postStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:postStr]];
NSLog(#"%#",postStr);
[request setHTTPMethod:#"POST"];
_connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
NSURL *url = [NSURL URLWithString:postStr];
NSData *data = [NSData dataWithContentsOfURL:url];
pJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"%#",pJson);
NSMutableArray *arr = [pJson objectForKey:#"Response"];
NSLog(#"%lu",(unsigned long)arr.count);
NSMutableDictionary *dict2 =[[NSMutableDictionary alloc]init];// [arr objectAtIndex:NSIndexPath.row];
[dict2 setObject:arr forKey:#"dictionary1"];
dict2 = [arr objectAtIndex:0];
NSArray *arr1 =[dict2 objectForKey:#"0"];
NSLog(#"%lu",(unsigned long)arr1.count);
NSUInteger y;
for (int i=0;i<arr.count;i++) {
NSString *ring_data = [[arr objectAtIndex:i]objectForKey:#"menuname"];
NSString *id_data = [[arr objectAtIndex:i]objectForKey:#"menuid"];
NSLog(#"AUTHOR: %#",ring_data);
NSLog(#"%#",id_data);
dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
ring_data,#"menuname",id_data,#"menuId",nil];
[myObject addObject:dictionary];
NSMutableArray *arr1 = [dict2 objectForKey:#"0"];
NSLog(#"%lu",(unsigned long)arr1.count);
y = arr.count;
for (NSUInteger i=0;i<arr1.count;i++) {
NSArray *count = [[[arr1 objectAtIndex:i] objectForKey:arr]valueForKey:#"catname"];
NSString *myCount = [NSString stringWithFormat:#"%lu",(unsigned long)[count count]];
NSString *ring_data = [[arr1 objectAtIndex:i]objectForKey:#"catname"];
NSLog(#"AUTHOR: %#",ring_data);
// NSLog(#"%#",catname_data);
dictionary1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
ring_data,#"catname",
nil];
[myObject1 addObject:dictionary1];
}
}
I tried some coding for you.Follow that code and customize where you want to add to array and where to set dictionary.
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[jsonArray objectForKey:#"Response"];
for (int i=0;i<[array count];i++)
{
NSMutableDictionary *dict = [array objectAtIndex:i];
NSMutableArray *arrayDictValue = [dict valueForKey:[NSString stringWithFormat:#"%d",0]];
NSString *strMenuName = [NSString stringWithFormat:#"%#",[arrayDictValue valueForKey:#"menuname"]];
NSString *strMenuID = [NSString stringWithFormat:#"%#",[arrayDictValue valueForKey:#"menuid"]];
NSLog(#"The strMenuName is-%#",strMenuName);
NSLog(#"The strMenuID is-%#",strMenuID);
for (int j=0; j<[arrayDictValue count]; i++)
{
NSMutableDictionary *dictInside = [arrayDictValue objectAtIndex:j];
NSArray *arrayInsideDict = [dictInside valueForKey:#"0"];
for (int k =0; k<[arrayInsideDict count]; i++)
{
NSString *strCatName = [NSString stringWithFormat:#"%#",[[arrayInsideDict objectAtIndex:k ]valueForKey:#"catname"]];
NSString *strCatID = [NSString stringWithFormat:#"%#",[[arrayInsideDict objectAtIndex:k ]valueForKey:#"catid"]];
NSLog(#"The strCateName is-%#",strCatName);
NSLog(#"The strCatID is-%#",strCatID);
NSMutableDictionary *dictInArray = [[arrayInsideDict objectAtIndex:0] valueForKey:#"0"];
NSString *strSCatName = [NSString stringWithFormat:#"%#",[dictInArray valueForKey:#"scatname"]];
NSString *strSCatID = [NSString stringWithFormat:#"%#",[dictInArray valueForKey:#"scatid"]];
NSLog(#"the strSCatName is - %#",strSCatName);
NSLog(#"the strSCatID is - %#",strSCatID);
}
}
}
I've been following a tutorial on youtube on how to load external data from a database on to a iOS application. I understand the concept and how it works etc. But I'm having an error even though I'm following the video and from looking online it seems to be a common error.
- (void) retrieveData
{
NSURL * url = [NSURL URLWithString: getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData: data options:kNilOptions error:nil];
//set up our cities array
citiesArray = [[NSMutableArray alloc] init];
// loop through our json array
for (int i =0; i< jsonArray.count; i++)
{
//create our city object
NSString * cID = [[jsonArray objectAtIndex:i] objectForKey:#"id"];
NSString * cName = [[jsonArray objectAtIndex:i] objectForKey:#"cityName"];
NSString * cState = [[jsonArray objectAtIndex:i] objectForKey:#"cityState"];
NSString * cPopulation = [[jsonArray objectAtIndex:i] objectForKey:#"cityPopulation"];
NSString * cCountry = [[jsonArray objectAtIndex:i] objectForKey:#"country"];
// Add the city object to our cities array
[citiesArray addObject:[[City alloc]initWithCityName:cName andCityState:cState andCityCountry:cCountry andCityPopulation:cPopulation andCityID:cID]];
}
//reload our table view
[self.tableView reloadData];
}
The code fails on the third line.
jsonArray = [NSJSONSerialization JSONObjectWithData: data options:kNilOptions error:nil];
Why is that? Any suggestions? The jsonArray has already been created, so I can't understand why it won't work.
I checked your code & i don't think there is any error.
I hope you've declared NSMutableArray *jsonArray in header (.h) file.
If you getting error in thos line :
jsonArray = [NSJSONSerialization JSONObjectWithData: data options:kNilOptions error:nil];
than replace kNilOptions with simply nil.
If you getting crash than it might be because nil data. In that case you have to put condition before you store data in array something like this :
if (data != nil)
{
jsonArray = [NSJSONSerialization JSONObjectWithData: data options:nil error:nil];}
Hope it'll help.
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];
}
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.