Objective C parse JSON - ios

I Have this result JSON below that i get from my wcf service which i want to iterate through in my ipad app.I use the code below to parse the result json but the app gives error. How can iterate through this dictionary and get the items.
IOS Code:
myArray = [NSMutableArray array];
// Do any additional setup after loading the view.
NSString* URL = #"http://www.unluapps.com/Service1.svc/ListTopReports";
NSDictionary *dictionary = [JSONHelper loadJSONDataFromURL:URL ];
NSString *result=[dictionary valueForKey:#"ListTopReportsResult"];
NSLog(#"%#",result);
/* for (NSString* key in result ) {
id value=[result objectForKey:key];
NSLog(#"%# -+",value);
}
*/
JSON:
{
ListTopReportsResult: [
{
AppUserID: null,
Author: "Joe Matthew",
Company: "Coca-Cola",
Country: "Poland",
CreationDate: "8/20/2014 4:32:00 AM",
EndDate: null,
ResearchReportID: "2",
Sector: "Soft Drinks",
Summary: "da ascon casmld lmasdlasd",
Title: "Can Coca-cola beat the market?",
URL: "2123123.pdf"
},
{
AppUserID: null,
Author: "martina pawlik",
Company: "Cimsa",
Country: "Poland",
CreationDate: "8/20/2014 4:31:00 AM",
EndDate: null,
ResearchReportID: "1",
Sector: "Cement",
Summary: "asd adas asd asdasd asdasdasd",
Title: "Poland's cement sector is on the rise",
URL: "1123123.pdf"
}
]
}

Try this:
NSArray *result=[dictionary valueForKey:#"ListTopReportsResult"];
Because in your JSON, there is an array for key ListTopReportsResult.
Hope this helps. :)

Try doing something like this. This is not the exact solution and you'll have to work around your way.
NSString *link = [NSString stringWithFormat:#"yourServiceURL"];
NSString *encdLink = [link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:encdLink];
NSData *response = [NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response options: NSJSONReadingMutableContainers error: &error];
Now you have your data in the array and extract it out using objectForKey or valueForKey.You can use NSDictionary or NSArray as per your requirement.
Firstly get the array from the above code. Then extract out the image content like this :
_demoArray = [json valueForKey:#"yourKeyField"];
Now you have the values in your demoArray.
Hope this helps.

Related

Parsing json having multiple arrays

I am stuck with JSON parsing in my code. I tried a lot but could not figure out what is going wrong.
This is my JSON response
[{
"order": {
"transaction_id": "bFnRjTPYfD",
"status": 0,
"created_at": "2015-04-22 09:35:35"
}
}, {
"order_items": [{
"item_id": 1,
"item_name": "Potato",
"item_description": null,
"item_salesprice": 14,
"item_imagepath": "\/uploads\/veggies\/potato.jpg",
"order_quantity": "4 Kg",
"order_price": 69.99
}, {
"item_id": 2,
"item_name": "Tomato",
"item_description": null,
"item_salesprice": 18,
"item_imagepath": "\/uploads\/veggies\/tomato.jpg",
"order_quantity": "6 Kg",
"order_price": 79.99
}]
}]
I want to extract transaction id and item name. Can you please help me with this?
Update Answer:
NSDictionary *Order=[JSONData ValueForKey:#"Order"];
NSString *transaction_id=[Order ValueForKey:#"Transaction_id"];
You can get transaction_id by this way,
NSDictionary *OrderJson=[jsonArray objectAtIndex:0];
NSDictionary *OrderDic = [OrderJson valueForKey:#"order"];
NSString *transactionId=[OrderDic objectForKey:#"transaction_id"];
ItemNames are in array, you can get it by for loop, or predicates, Here I show you with for
NSDictionary *order_itemsJson=[jsonArray objectAtIndex:1];
NSArray *item=[order_itemsJson objectForKey:#"order_items"];
for (NSDictionary *dic in item) {
NSLog(#"%#",[dic valueForKey:#"item_name"]);
}
Enjoy Coding !!
Do the following things, you will get output.
NSString* transectionId = [[[arrayResponse objectAtIndex:0] valueForKey:#"order"] valueForKey:#"transaction_id"];
NSLog(#"transectionId : %#",transectionId);
NSArray* arrayInner = [[arrayResponse objectAtIndex:1] valueForKey:#"order_items"];
for (int i=0; i<arrayInner.count; i++) {
NSDictionary* dictInner = [arrayInner objectAtIndex:i];
NSString* itemName = [dictInner valueForKey:#"item_name"];
NSLog(#"Item Name : %#",itemName);
}
Here you will get transaction_id and item_name
Hope this help you.
Try it.. For Transaction id..
NSDictionary *Order=[JSONData ObjectForKey:#"Order"];
NSString *transaction_id=[Order ValueForKey:#"Transaction_id"];
and For item_id try,...
NSDictionary *item=[JSONData objectForKey:#"order_items"];
NSArray *item_id=[Order ValueForKey:#"item_name"];

Unable to create keys into NSDictionary after parsing JSON

I have seen similar topics to this but none that seem to address my issue. I am receiving this JSON:
("taskname: 1738 Main St., taskdescription: install flooring, worker: Jim Davis, approver: John Jones",
"taskname: 300 Market St., taskdescription: paint ceiling, worker: John Smith, approver: Bob Johnson"
)
This is the code that I am using to ultimately create a NSDictionary:
NSURL *url = [NSURL URLWithString:MY_JSON_URL];
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:NULL];
NSArray *JSONarray = [JSONDictionary valueForKeyPath:#"feed.entry.content.$t"];
NSDictionary *taskDictionary = JSONarray[0];
NSLog(#"array content = %#",JSONarray)
The array values are correct but when I try to key into the dictionary, the key does not exist
NSLog(#"dictionary contents = %#", taskDictionary[#"taskname"]);
I am new to JSON so any help is much appreciated!
The JSON you are receiving is not valid, hence the key 'taskname' doesn't exist.
It should be in the following format:
[{"taskname": "1738 Main St.", "taskdescription": "install flooring", "worker": "Jim Davis", "approver": "John Jones"},
{"taskname": "300 Market St.", "taskdescription": "paint ceiling", "worker": "John Smith", "approver": "Bob Johnson"}]

Multi level JSON reading and writing IOS8

So the last two days I have been struggling to get data from and to a JSON file, this is because it has multiple levels and the same names. I did not set up this file and can't change the structure so I have to get it working in the way it is. To Pharse JSON form a single level is no problem and it works fine, what I need is to get separate data block from "GOV" and "PRIV" then I need a data block "GENERAL" and "LOCAL" and within those I need to be able to get the "Hospital information as a block but also the separate values. Now I have been trying to get this done for two days and I know im doing something wrong but cant figure it out. I do get data back for example the "GOV" block but then in the output window it is showing a array with access data (<__NSCFArray 0x7fe711f58800>) and the output... I cant break up this output and that is what I need because every value needs to be in a text file in a tableview cell. I know { } denotes NSDictionary [ ] denotes NSArray and I have been reading a lot about JSON and I get the concept but There is little to non for me understandable info when it comes to multi level JSON and equal names (hospital) in this case. I have tried all the available option I could find here on StackOverflow but no succes. So if somebody can push me in the right way I will be gratefull.. part of the code:
NSURL *url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
_jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
_AppListArray = [[NSMutableArray alloc] init];
NSArray *wrapper= [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *avatars = [wrapper objectAtIndex:0];
for(NSDictionary *apps in _jsonArray) {
if([[apps objectForKey:#"title"] isEqualToString:#"GOV"]){
NSDictionary*tmp = [apps objectForKey:#"hospital"];
_AppListArray = [tmp objectForKey:#"area"];
}
}
//returns error because _ApplistArray is an array and it can't read the data from the objectkey
for (int i = 0; i < _jsonArray.count; i++)
{
NSString *appName = [[_AppListArray objectAtIndex:i] objectForKey:#"hospitalname"];
NSString *appCondition = [[_AppListArray objectAtIndex:i] objectForKey:#"condition"];
NSString *app avgrating = [[_AppListArray objectAtIndex:i] objectForKey:#"avgrating"];
[_AppListArray addObject:[[Applist alloc]initWithAppName:appName andAppCondition:appCondition andAppURL:appURL]];
}
The _ApplistArray does return the 1ste Hospital data block but as an array and this is were I get stuck.. I need to get another level deeper.....Again the solution probably is easy but JSON is something I never worked with this is my first go. The JSON where I need to get the data from:
[
-{
-hospital: {
-area: [
-{
-hospital: [
-{
hospitalname: "ABC",
avgrating: "2,6",
condition: "UPDATE NEEDED",
},
-{
hospitalname: "DEF",
avgrating: "4,2",
condition: "FINE",
},
],
name: "GENERAL"
}
]
},
title: "GOV"
},
-{
-hospital: {
-area: [
-{
-hospital: [
-{
hospitalname: "GHI",
avgrating: "3",
condition: "INSTALL NEW",
},
-{
hospitalname: "JKL",
avgrating: "0",
condition: "NEW",
},
],
name: "LOCAL"
}
]
},
title: "PRIV"
}
]
Here you go.
NSArray *hospitals = [jsonArray objectForKey:#"mainKey"];// I assumed you getting with some key but change based on your requirement
for (NSDictionary *mainData in hospitals){ // Start of Main Hospital
NSDictionary *hospital = [mainData objectForKey:#"hospital"];
NSArray *areas = [hospital objectForKey:#"area"];
for(NSDictionary *area in areas){// Start of Area
NSArray *innerHospitals = [area objectForKey:#"hospital"];
for(NSDictionary *innerHospital in innerHospitals){
NSString *hospitalName = [innerHospital objectForKey:#"hospitalname"];
NSString *avgrating =[innerHospital objectForKey:#"avgrating"];
NSString *condition =[innerHospital objectForKey:#"condition"];
// Do What Ever you want here
}
NSString *name =[area objectForKey:#"name"];
}// End Of Area
NSString *title =[mainData objectForKey:#"title"];
} // End of Main Hospital
I haven't tested it. But i assume this will work. Have a try and let me know what happens.
The problem is that you need 2 for loops for each "Area".
Area is an Array (1st loop) and each hospital is another Array (2nd loop).
And inside each hospital element is the dictionary with the values you need.
ignoring loops this is how you get the first hospitalname(ABC) assuming _AppListArray has the contents of Area
NSString *appName = _AppListArray[0][#"hospital"][0][#"hospitalname"];
For each 0 you will replace it with the counters for the for loops.

How do I gather JSON data nested in an array using NSDictionary

I have the following JSON:
{
0: 200,
error: false,
campaigns: {
current_campaigns: [
{
id: "1150",
campaign_type_id: "1",
campaign_type: "Type",
title: "Name (with type) ",
url: "http://www.example.com",
special: null,
campaign_instructions: "Here's what you do",
pay_description: "",
start: "2013-10-14 00:00:00",
end: "2014-03-31 23:59:59"
},
{
id: "1151",
campaign_type_id: "1",
campaign_type: "Type",
title: "Name (with type) ",
url: "http://www.example.com",
special: null,
campaign_instructions: "Here's what you do",
pay_description: "",
start: "2013-10-14 00:00:00",
end: "2014-03-31 23:59:59"
},
],
new_campaigns: [
{
id: "1152",
campaign_type_id: "1",
campaign_type: "Type",
title: "Name (with type) ",
url: "http://www.example.com",
special: null,
campaign_instructions: "Here's what you do",
pay_description: "",
start: "2013-10-14 00:00:00",
end: "2014-03-31 23:59:59"
}
]
}
And the following code
NSURL *theJSON = [NSURL URLWithString:#"http://somejsonurl"];
NSURLRequest *request = [NSURLRequest requestWithURL:theJSON];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
NSError *errorJson = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&errorJson];
NSArray *campaigns = dataDictionary[#"campaigns"];
for (NSDictionary *campaignList in campaigns) {
NSLog(#"Call gave: %#", campaigns);
}
How would I end up logging the current_campaign title?
I tried
NSLog(#"%#", [campaignList objectForKey:#"title"]);
NSLog(#"%#", campaigns[#"title"] );
and no success. I'm fairly new at Objective C and am having trouble understanding how you dig into JSON with NSArray and NSDictionary. Any help would be greatly appreciated!
The easiest thing to remember about JSON is that every time you see a bracket "[", that means the beginning of an Array and "]" is the end. Every time you see a curly brace "{" that means the beginning of a Dictionary and "}" is the end.
So in your example, campaigns is a Dictionary element with another Dictionary (current_campaigns) that contains an Array of Dictionaries. Each of those Dictionaries has a key called title.
So the long version (untested):
NSDictionary *campaigns = [dataDictionary objectForKey:#"campaigns"];
NSArray *currentCampaigns = [campaigns objectForKey:#"current_campaigns"];
for (NSDictionary *thisCampaign in currentCampaigns) {
NSLog(#"title: %#", [thisCampaign objectForKey:#"title"]);
}

Convert text into json in Objective c

I have a string that I want to convert it into JSON in iOS but it is returning nil when I'm parsing it using jsonkit. My string format is as follows.
[
{ index:0, title:ARPPU },
{ index:1, title:ARPU },
{ index:2, title:Conversion },
{ index:3, title:DAU },
{ index:4, title:DAU },
]
Any one have idea how I can convert into a JSON object? Any help is appreciated.
The problem I would see here is your JSON string is invalid. Validate your JSON here
Try this
NSString *strJson = #"[{\"index\": \"0\",\"title\": \"ARPPU\"}]";
id jsonObj = [NSJSONSerialization JSONObjectWithData:[strJson dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers error:nil];
This worked for me.
Convert your string to NSData with NSUTF8Encoding and do a JSONSerialisation to make it JSON
// Converting Your String to NSData
NSString *myString=#"[
{ index:0, title:ARPPU },
{ index:1, title:ARPU },
{ index:2, title:Conversion },
{ index:3, title:DAU },
{ index:4, title:DAU },
]";
// Converts the string to Data
NSData* data = [myString dataUsingEncoding:NSUTF8StringEncoding];
// Does JSONSerialisation and convert the data into JSON
NSDictionary*dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// Prints here the JSON
NSLog(#"Dict value==%#",dict);
First fix the JSON string, see Introducing JSON and W3Schools.
Then it is a JSONstring representation.
Convert to NSData and use JSONObjectWithData:options:error:
NSString *JSONStringRepresentation= #"["
#"{ \"index\":0, \"title\":\"ARPPU\" },"
#"{ \"index\":1, \"title\":\"ARPU\" },"
#"{ \"index\":2, \"title\":\"Conversion\" },"
#"{ \"index\":3, \"title\":\"DAU\" },"
#"{ \"index\":4, \"title\":\"DAU\" },"
#"]";
NSData *JSONAsData = [JSONStringRepresentation dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSArray *JSONAsArrayObject = [NSJSONSerialization JSONObjectWithData:JSONAsData options:0 error:&error];
NSLog(#"JSONAsArrayObject: %#", JSONAsArrayObject);
NSLog output:
JSONAsArrayObject: (
{
index = 0;
title = ARPPU;
},
{
index = 1;
title = ARPU;
},
{
index = 2;
title = Conversion;
},
{
index = 3;
title = DAU;
},
{
index = 4;
title = DAU;
} )

Resources