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

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"]);
}

Related

NSDictionary valueForKeyPath returns nill even the keypath exists

Here are 2 lines from my app. The first one works properly and I get the value "LE-05330" on the label but for the second one I get nil. What am I doing wrong for the second line?
//Working properly
self.lblSerialNo.text = [self.PartInfo valueForKeyPath:#"veri.parca_bilgisi.referans_no"];
//valueForKeyPath returns nil so label is empty.
self.lblCertNo.text = [self.PartInfo valueForKeyPath:#"veri.sertifika.sertifika_no"];
The JSON data on the self.PartInfo object is below;
{
"durum": true,
"hata": "",
"veri": {
"parca_bilgisi": {
"imaj": "http://www.mywebsite.com:9898/mobapp/images/arac_hasar/arac-onsolkapi.jpg",
"parca_tanimi": "ÖN SOL KAPI",
"marka": "MYBRAND",
"marka_kodu": "70",
"model": "MYMODEL",
"model_kodu": "?",
"yil": "2005",
"uretici": "MYManufacturer.",
"referans_no": "LE-05330",
"oem_no": "999999",
"durum": "3",
"durum_aciklama": "Transferred_to_Supplier"
},
"onarim_servis_bilgileri": {
"servis_adi": "?",
"iletisim_no": "?",
"islem_tarihi": "?",
"hasar_dosya_no": "?"
},
"sigorta_bilgileri": {
"firma_adi": "?",
"iletisim_no": "?",
"ilgili_kisi": "?"
},
"eksper_bilgileri": {
"onaylama_tarihi": "?"
},
"uretici_bilgileri": {
"firma": "My Firm AS.",
"imaj": "harita.jpg",
"adres": "Carrer de Jacint Verdaguer, 58, 08970",
"eposta": "myr#email.es",
"tel": "+36 56565 345 317",
"web": "www.styaasira.es",
"kayit_tarihi": "7.7.2017 13:27:44",
"durum": "3"
},
"sertifika": {
"sertifikasyon_kurulusu": "87",
"sertifika_no": "87",
"gecerlilik_tarihi": "87"
}
}
}
My code to for retrieving NSDictionary (dict)
NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil) {
// Success
NSMutableDictionary* dict = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
I eliminated the service call, and tried the same JSON as string, still no chance...
NSString *json = ...
NSError *error;
NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableLeaves
error:&error];
self.lblIssuer.text = [dict valueForKeyPath:#"veri.sertifika.sertifikasyon_kurulusu​"];
After several unsuccessful logical tries, I decided to focus on the data and tried to modify(simplfy) the JSON object and try to see if it works on different key names. So I first changed the name of the node from "sertifika" to "test" and the 3 sub node names to "a", "b" and "c". With this state I was able to get the value using valueForKeyPath. Then, I changed the name of the nodes back to original, and it also worked!!! Then I commented out reading JSON from constant string to service response,... wait for it... it also worked!!!....
Can anybody tell something logical about what was going on? Is there a some sort of hashing mechanism for the NSDictionary that had gone crazy? Anyway, changing the node names that fails and then back to original has solved my problem...

sqlite command in iOS

Here I am using Sqlite Database for my Application, and my Database Table contains the column keyjson and values in rows are like below
{"filename":"21-01-3-02","label":""}
{"filename":"02-C-4-1","label":"17"}
{"filename":"14-L-3-2","label":"Nord Est"}
{"filename":"02-Z-5-1NouvelleIndustrieSectionValton","label":"1810"}
json data sas string
now I need to particular string that like
02
1
2
1NouvelleIndustrieSectionValton
from that particular column .
can anyone know the query for it,
Please replay me
&regards
You can do that without SQLite query. First, convert your JSON to a NSMutableArray :
NSData *data = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
Then you can parse it easily as follow :
NSMutableArray *finalResult = [NSMutableArray array];
NSString *filename;
for (id e in res){
filename = [e objectForKey:#"filename"];
[finalResult addObject:[[filename componentsSeparatedByString:#"-"] lastObject]];
}
// Here we go, finalResult contains the values you want
The problem is that your "JSON" is not valid JSON. It should look like this if you want it works :
[
{
"filename": "21-01-3-02",
"label": ""
},
{
"filename": "02-C-4-1",
"label": "17"
},
{
"filename": "14-L-3-2",
"label": "Nord Est"
},
{
"filename": "02-Z-5-1NouvelleIndustrieSectionValton",
"label": "1810"
}
]

Objective C parse JSON

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.

how to post manually created json object in ios

Please help me. I want to post this json data which I created manually. And I'm getting error as Object reference not set to an instance of an object.
{
customerId = 81;
lstOrderItems = (
{
itemId = 149;
itemQnt = 1;
itemTotalPrice = 205;
lstOrderAttribute = (
{
attributeId = 135;
lstOrderAttributeValue = (
{
attributeValueId = 173;
},
{
attributeValueId = 174;
}
);
}
);
},
{
itemId = 129;
itemQnt = 1;
itemTotalPrice = 205;
lstOrderAttribute = (
{
attributeId = 119;
lstOrderAttributeValue = (
{
attributeValueId = 143;
},
{
attributeValueId = 144;
},
{
attributeValueId = 145;
},
{
attributeValueId = 155;
}
);
},
{
attributeId = 120;
lstOrderAttributeValue = (
{
attributeValueId = 146;
},
{
attributeValueId = 147;
}
);
},
{
attributeId = 124;
lstOrderAttributeValue = (
{
attributeValueId = 158;
},
{
attributeValueId = 165;
}
);
}
);
},
{
itemId = 132;
itemQnt = 1;
itemTotalPrice = 205;
lstOrderAttribute = ( );
},
{
itemId = 144;
itemQnt = 1;
itemTotalPrice = 205;
lstOrderAttribute = ( );
}
);
orderTotalPrice = 291;
outletId = 54;
}
To make your life a bit easier i won't suggest you to construct a json on your own, instead make a dictionary (or array, as per the need) and pass it to json serializer, it will construct a valid json for you (if possible).
Sample code:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:userFirstName, #"fname", userLastName, #"lname", nil];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted error:&error];
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSLog(#"json : %#", json);
Output log:
2014-03-18 12:03:19.393 DesignMantic[1351:70b] json : {
fname = John;
lname = Doe;
}
Pass the constructed json to your service and you are free to invalid json issues.
Reference:
how to create json in objective-c
Hope it helps!
EDIT
Possibly, the data is not serialized to a valid json (may be because it is not convertable to json) and returned nil. You should check it first if the data is converted to json or not rty like this:
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:infoDictionary options:NSJSONWritingPrettyPrinted error:&error];
if(jsonData && [NSJSONSerialization isValidJSONObject:jsonData])
{
NSString *postString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *url = [NSString stringWithFormat:#"sqwip.ignivainfotech.net/api/customerapi/…"];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:url]];
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
}
else
{
// Through error, since data sent for JSON serialisation is not convertible to json format
}
Your JSON Format is inValid
JSON Syntax Rules
JSON syntax is a subset of the JavaScript object notation syntax:
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
you must have your Format like below one
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"height_cm": 167.64,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
}
JSONLint is a great way to find out what's wrong with hand-coded JSON.  There are both command-line and web-based versions.
If you were to paste the above JSON into JSONLint.com, you would see that one of the first mistakes you're making is using hash keys that aren't strings.  Fix that, and there may be other errors you'll need to correct.
You'll learn the restrictions of JSON gradually and iteratively using a lint program like this.  Good luck.

Trouble With RKMappingResult. Can't find a way to get NSDictionary from result

I am trying to incorporate RestKit v.20 into my iOS App. I get the proper mapping result from RKObjectRequestOperation but I can't figure out a good way to put it into a NSDictionary. I am returned an array of objects of hex values. I can get the values of all the specific items I want by using objectAtIndex: but I need a place that has all the values in its string format, not hex. I can only change from hex to string by setting the associated class equal to a single array object. I want a general list so I can predicate it for use in search.
Here is the JSON Data:
{
"carsInShop": [
{
"car": {
"id": "1",
"name": "Mercedes",
"year": "2000"
}
},
{
"car": {
"id": "2",
"name": "BMW",
"year": "2004"
}
},
{
"car": {
"id": "3",
"name": "Audi",
"year": "2001"
}
},
{
"car": {
"id": "4",
"name": "Lexus",
"year": "2011"
}
},
{
"car": {
"id": "5",
"name": "Toyota",
"year": "2006"
}
},
],
"count": 5
}
Here is where I am having code problems:
NSURL *URL = [NSURL URLWithString: #"http://localhost:8888/testphpread/index.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
RKObjectRequestOperation *objectRequestOperation = [[RKObjectRequestOperation alloc] initWithRequest:request
responseDescriptors:#[responseDescriptor]];
[objectRequestOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
RKLogInfo(#"CarsInShopArray: %#", mappingResult.array);
carsInShopArray = [mappingResult array];
CarsInShop* carsInShop = [carsInShopArray objectAtIndex:0];
NSLog(#"Loaded Car ID #%# -> Name: %#, Year: %#", carsInShop.car.id, carsInShop.car.name, carsInShop.car.year);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(#"Operation failed with error: %#", error);
}];
This is what I get from NSLog:
CarsInShopArray: (
"CarsInShop: 0xa26b0f0",
"CarsInShop: 0xa46b2f0",
"CarsInShop: 0xa46af20",
"CarsInShop: 0xa46b7a0",
"CarsInShop: 0xa46bd90",
)
Loaded Car ID #1 -> Name: Mercedes, Year: 2000
So you see I can get individual items, but I need to access the dictionary as a whole, for use in searching.
You have a custom class CarsInShop, I guess it inherits from NSObject. You don't override the description method so you get the default description when you log the instance. The default is the class name and its pointer. That's why you get "CarsInShop: 0xa26b0f0". It says nothing about the contents of the instance.
When you say: "I need to access the dictionary as a whole", you don't have a dictionary. You have an array of custom objects. You can still use KVC to search through the items in the array (based on key path by the look of your log statement).
You can get an array of the cars by doing:
NSArray *cars = [carsInShopArray valueForKey:#"car"];

Resources