i am newbie in iOS Development. i want to parse my this JSON Data into to array First array Contain all Data and Second array Contain only -demopage: array Value.
status: "success",
-data: [
{
mid: "5",
name: "October 2014",
front_image: "http://www.truemanindiamagazine.com/webservice/magazineimage/frontimage/01.jpg",
title: "October 2014",
release_date: "2014-10-01",
short_description: "As the name suggest itself “Trueman India” will cover icons of India. Our national Magazine “Trueman India” is an expansion to our business, i",
current_issue: 0,
-demopage: [
{
link: "http://www.truemanindiamagazine.com/webservice/magazineimage/pageimage/2014/10/01-1413806104.jpg",
page_no: "1"
},
{
link: "http://www.truemanindiamagazine.com/webservice/magazineimage/pageimage/2014/10/2-1413806131.jpg",
page_no: "2"
},
{
link: "http://www.truemanindiamagazine.com/webservice/magazineimage/pageimage/2014/10/3-1413806170.jpg",
page_no: "3"
}
]
}
]
Here my main Dictionary Key is data i want data keey value in my One array and demopage key value in to another array here my two Array is self.imageArray and self.imagesa here my code For that
- (void)viewDidLoad
{
[super viewDidLoad];
[self.collectionView registerNib:[UINib nibWithNibName:#"CustumCell" bundle:nil] forCellWithReuseIdentifier:#"CellIdentifier"];
dispatch_async(kBgQueue, ^{
data = [NSData dataWithContentsOfURL: imgURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
-(void)fetchedData:(NSData *)responsedata
{
NSMutableArray *imagesArray = [[NSMutableArray alloc]init];
if (responsedata.length > 0)
{
NSError* error;
self.json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
if ([[_json objectForKey:#"data"] isKindOfClass:[NSArray class]])
{
NSArray *arr = (NSArray *)[_json objectForKey:#"data"];
[self.imageArray addObjectsFromArray:arr];
[self.storeTable reloadData];
}
self.storeTable.hidden=FALSE;
for (index=0; index<[self.imageArray count]; index++)
{
for(NSDictionary *dict in self.imageArray)
{
imagesArray = [dict valueForKey:#"demopage"];
self.imagesa = imagesArray;
}
NSLog(#"New Demo page array %#",self.imagesa);
}
}
then i get my data key value and it is ok but i got only last index means here my -data key Contain three -demopage key and i get only last -demopage key value i want all -demopage key value in to self.imagesa please give me solution for that.
also my Webservices link is Link
First get -data in NSMutableArray.
NSMutableArray *dataArray = [[NSMutableArray alloc]init];
NSMutableArray *imagesArray = [[NSMutableArray alloc]init];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
dataArray=[json objectForKey:#"data"];
for(NSDictionary *dict in dataArray )
{
imagesArray = [dict valueForKey:#"demopage"];
self.imagesa = imagesArray;
}
[selt.tableView reloadData];
You can give it a try like this:
NSError* error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
NSDictionary *dataDict = [json objectForKey:#"data"];
NSArray *imageArray = [dataDict objectForKey:#"demopage"];
self.imagesa = [NSMutableArray array];
for (NSDictionary *dict in array) {
NSString *imageUrl = [dict objectForKey:#"link"];
[self.imagesa addObject:imageUrl];
}
Then you got imageArray as dataSource for the collectionView.
I would use SBJson library, but not the last 4th version:
pod 'SBJson', '3.2'
Sample code, I changed variable names and formatting a little bit:
// Create a JSON String from NSData
NSData *responseData = [NSData new]; // Here you should use your responseData
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
if (! jsonString ) {
// Handle errors
}
// Create SBJsonParser instance
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
// Parse JSON String to dictionary
NSDictionary *jsonDic = [jsonParser objectWithString:jsonString];
// Get an array by key
NSArray *dicArray = [jsonDic objectForKey:#"demopage"];
// Reload collection view
if ( [dicArray count] > 0 ) {
dispatch_async(dispatch_get_main_queue(), ^{
// Reload Your Collection View Here and use dicArray (in your case imagesa array with dictionaries)
});
}
And when you set a cell, you can use something like this:
NSDictionary *dic = dicArray[indexPath.row];
NSString *link = dic[#"link"];
NSString *pageNo = dic[#"page_no"];
Related
I have a JSON like below (getting from an URL)-
{
action :getAllJournal;
data :{
journalList :[{
cancelled : F;
"cust_code" : "700-T022";
"journal_amount" : 2216;
"journal_code" : "JV1603/001";
"journal_date" : "2016-03-15 00:00:00";
"journal_id" : 1;
outstanding : 0;
},
{
cancelled : F;
"cust_code" : "700-0380";
"journal_amount" : 120;
"journal_code" : "JV1605/006";
"journal_date" : "2016-05-31 00:00:00";
"journal_id" : 2;
outstanding : 120;
},
{
cancelled : F;
"cust_code" : "700-T280";
"journal_amount" : 57;
"journal_code" : "JV1609/001";
"journal_date" : "2016-09-22 00:00:00";
"journal_id" : 3;
outstanding : 0;
}
];
};
message = "";
"message_code" = "";
result = 1;}
The code below doing is getting the JSON from URL and storing them in NSMutableArray. Until storing them into array, it's working fine but I'm bit confused with the JSON format and don't know how to get result by a key.
__block NSMutableArray *jsonArray = nil;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:#"http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
{
if (data)
{
id myJSON;
#try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
#catch (NSException *exception) {
}
#finally {
}
jsonArray = (NSMutableArray *)myJSON;
NSString *nsstring = [jsonArray description];
NSLog(#"IN STRING -> %#",nsstring);
NSData *data = [nsstring dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if(jsonObject !=nil){
if(![[jsonObject objectForKey:#"journalList"] isEqual:#""]){
NSMutableArray *array=[jsonObject objectForKey:#"journalList"];
NSLog(#"array: %lu",(unsigned long)array.count);
int k = 0;
for(int z = 0; z<array.count;z++){
NSString *strfd = [NSString stringWithFormat:#"%d",k];
NSDictionary *dicr = jsonObject[#"journalList"][strfd];
k=k+1;
// NSLog(#"dicr: %#",dicr);
NSLog(#"cust_code - journal_amount : %# - %#",
[NSMutableString stringWithFormat:#"%#",[dicr objectForKey:#"cust_code"]],
[NSMutableString stringWithFormat:#"%#",[dicr objectForKey:#"journal_amount"]]);
}
}
}else{
NSLog(#"Error - %#",jsonError);
}
}
}];
From this, I am able to get the JSON successfully. But it's always giving me this error: Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in an object around character 6." UserInfo={NSDebugDescription=No string key for value in an object around character 6.} How can I get all values from journalList? I'm new to iOS, that's why not sure what I'm missing.
id myJSON;
#try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
#catch (NSException *exception) {
}
#finally {
}
jsonArray = (NSMutableArray *)myJSON;
NSString *nsstring = [jsonArray description];
NSLog(#"IN STRING -> %#",nsstring);
NSData *data = [nsstring dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
I'd say: NO and NO.
I wouldn't do a #try/#catch on a NSJSONSerialization, because the real issues are on the error parameter (and they won't throw a NSException for most of the cases). Just check if (data) is quite efficient.
Then, let's say it worked, and you have myJSON.
In fact, myJSON is a NSDictionary, not a NSArray, so the cast is useless and doesn't make sense.
Next issue:
Your are using -description (okay, if you want to debug), but you CAN'T use it to reconstruct AGAIN a JSON. It's not a valid JSON, it's the way the compiler "print" an object, it adds ";", etc.
If your print [nsstring dataUsingEncoding:NSUTF8StringEncoding] and data you'll see that they aren't the same.
For a more readable:
NSString *dataJSONStr = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];, it's clearly not the same structure as your nsstring.
Then, you are redoing the JSON serialization? Why ?
So:
NSError *errorJSON = nil;
NSDictionary *myJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&errorJSON];
if (errorJSON)
{
NSLog(#"Oops error JSON: %#", errorJSON);
}
NSDictionary *data = myJSON[#"data"];
NSArray *journalList = data[#"journalList"]
for (NSDictionary *aJournalDict in journalList)
{
NSUInteger amount = [aJournalDict[#"journal_amount"] integerValue];
NSString *code = aJournalDict[#"journal_code"];
}
There is a dictionary named "data" you're not fetching, represented by {}.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if (!jsonError) {
// Fetch the journalList
NSArray *journalList = json[#"data"][#"journalList"];
// iterate over every entry and output the wanted values
for (NSDictionary *journal in journalList) {
NSLog(#"%# %#", journal[#"cust_code"], journal[#"journal_amount"]);
}
}
json[#"key"] is a short form of [json objectForKey:#"key"] I find easier to read.
That is not a valid JSON. Entries should be separated by comma ,, not semicolon ;
You need to fetch journalList from data.
Try below code:
This is demo code to create array like you:
NSMutableDictionary *jsonObject = [NSMutableDictionary new];
jsonObject[#"action"]= #"";
jsonObject[#"message"]= #"";
jsonObject[#"message_code"]= #"";
jsonObject[#"result"]= #"1";
NSMutableArray *ary1 = [NSMutableArray new];
for(int i=0;i<5;i++)
{
NSMutableDictionary *dd = [NSMutableDictionary new];
dd[#"cancelled"]= #"F";
dd[#"cust_code"]= #"F";
[ary1 addObject:dd];
}
NSMutableDictionary *dicjournal = [NSMutableDictionary new];
[dicjournal setObject:ary1 forKey:#"journalList"];
[jsonObject setObject:dicjournal forKey:#"data"];
This is main Logic:
NSMutableArray *journalList = [NSMutableArray new];
NSMutableDictionary *dic = [jsonObject valueForKey:#"data"];
journalList = [[dic objectForKey:#"journalList"] mutableCopy];
Looks like your JSON is invalid. You can see whether your JSON is correct or not using http://jsonviewer.stack.hu/ and moreover format it. Meanwhile your code is not using "data" key to fetch "journalList" array.
Code : -
NSDictionary *dic = [jsonObject valueForKey:#"data"];
NSMutableArray *arr = [dic objectForKey:#"journalList"];
for (int index=0 ; index < arr.count ; index++){
NSDictionary *obj = [arr objectAtIndex:index];
// Now use object for key from this obj to get particular key
}
Thanks #Larme and #Amset for the help. I was doing wrong the in the NSMutableArray part. The correct version of this code is in the below:
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:#"http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
{
if (data)
{
id myJSON;
#try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
#catch (NSException *exception) {
}
#finally {
}
NSArray *journalList = myJSON[#"data"][#"journalList"];
for (NSDictionary *journal in journalList) {
NSLog(#"%# %#", journal[#"journal_date"], journal[#"journal_amount"]);
}
}
}];
I want to create a JSON like this
[{"phone":"3456345"}, {"phone":"2423242"}, {"phone":"2423423"}]
I have an array in which i have phone numbers only. Below code will create the JSON but for that i need to create dictionary first.
contactData =[NSJSONSerialization dataWithJSONObject:contacts options:NSJSONWritingPrettyPrinted error:&error];
I have tried to create Dictionary like this but it only enter last value because i can't have duplicate value for one key. please tell me how do i solve the problem?
int i=0;
for (i=0; i<[all_contacts count]; i++)
{
[contacts setObject:[all_contacts objectAtIndex:i] forKey:#"phone"];
}
How can i create the json here.Please tell?
Assuming all_contacts looks like this:
[ "3456345", "2423242", "2423423" ]
Then this should work:
NSMutableArray *root = [NSMutableArray new];
for (NSString *number in all_contacts) {
[root addObject:#{ "phone": number }];
}
contactData =[NSJSONSerialization dataWithJSONObject:root
options:NSJSONWritingPrettyPrinted
error:&error];
int i=0;
NSMutableArray *contacts = [[NSMutableArray alloc] init];
for (i=0; i<[all_contacts count]; i++) {
[contacts addObject:#{#"phone" : [all_contacts objectAtIndex:i]}];
}
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:contacts options:0 error:&error];
if (!jsonData) {
//error here
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
I need to get Particular Object values ( A, B, C, D) and related key values (#"name" ). Here below I have posted my sample code and response. Please help me.
NSString *combined = URL;
NSURL *url = [[NSURL alloc] initWithString:combined];
NSData *responseData=[NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray *responsData = [jsonDictionary objectForKey:#"response"];
// GET A,B,C Object values
NSDictionary *d1 = responsData.firstObject;
NSEnumerator *enum1 = d1.keyEnumerator;
NSArray *firstObject = [enum1 allObjects];
My JSON Response :
response : [ {
A = [ {
name : tango
}
{
name : ping
}
]
B = [ {
name : tango
}
{
name : ping
}
]
} ]
You can achieve the list of all names using this:
NSMutableArray *names = [[NSMutableArray alloc] init];
for (NSDictionary *dict in responsData) {
[dict enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
NSArray *valueArray = (NSArray *)obj;
for (NSDictionary * namesDict in valueArray) {
[names addObject:namesDict[#"name"]];
}
}];
}
Output:
NSLog(#"Names %#",names);
tango, ping, tango, ping.
Hope that helps!
Simply
for(NSDictionary *dict in firstObject){
NSLog(#"%#",[dict objectForKey:#"name"]);
}
i just get started with Ios programming, and i have to parse a nested Json file and extract the items and lables, the problem is i have to display the list of the items on a tableview and refresh my tableview everytime i click on a row of my table view:
i did display the first list of my items but i'm trying to display my nested items and display them on my "new" tableview:
here are a simple of my JSON code and my objective-c code:
"results": {
"items": [
{
"id": "0100",
"label": "Actualités",
"cover": "http://XXXX_01.jpg",
"coverFrom": "XXX-03",
"coverTo": "2031-CCC18",
"coverOrder": 1,
"items": [
{
"id": "0101",
"label": "Actualité / Infos",
"cover": "http://XXXX.jpg",
"coverFrom": "2014XXX-24",
"coverTo": "2031-XXXX18",
"coverOrder": 1,
"items": [
]
},
and my RootViewContoller contain this code of the function connectionDidFinishiongLoading**
// we will follow the format of our nested JSON
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:dataRequest options:0 error:nil];
NSDictionary *results = [allDataDictionary objectForKey:#"results"];
NSArray *arrayOfItems = [results objectForKey:#"items"];
for (NSDictionary *diction in arrayOfItems) {
//NSArray *ide = [diction objectForKey:#"id"];
NSString *label = [diction objectForKey:#"label"];
// add new object founded
[array addObject:label];
}
// reload my tableview
[[self tableView]reloadData];
// myParsingResults = [NSJSONSerialization JSONObjectWithData:dataRequest options:nil error:nil];
[[self tableView]reloadData];
If I understood correctly, try something like that:
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:dataRequest options:0 error:nil];
NSDictionary *results = [allDataDictionary objectForKey:#"results"];
NSArray *array = [results objectForKey:#"items"];
NSMutableArray *arrayLabels = [[NSMutableArray alloc] init];
NSDictionnary *dicoTemp = [array objectAtIndex:0];
while([dicoTemp objectForKey:#"items"])
{
arrayLabels addObject:[[dicoTemp objectForKey:#"items"] objectForKey:#"label"];
NSArray *arrayTemp = [dicoTemp objectForKey:#"items"];
dicoTemp = [arrayTemp objectAtIndex:0]; //I don't know how you JSON ends, you may have to check if [arrayTemp count] > 0. I presumed that at the end, there was no object for key "items"
}
[[self tableView] reloadData];
That a weird nested JSON response, in my opinion.
Try this one...
NSError *error = nil;
NSURL *Url = [[NSURL alloc] initWithString:#"Your URL"];
jsonData = [NSData dataWithContentsOfURL:Url options:NSDataReadingUncached error:&error];
if(jsonData==Nil){
UIAlertView * alert=[[UIAlertView alloc]initWithTitle:#"Error" message:#"Please check your internet connection" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:#"ok", nil];
[alert show];
}
else{
NSDictionary *dataDictionary =[[NSDictionary alloc]init];
dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
[array addObject:[[[dataDictionary objectForKey:#"results"] valueForKey:#"items"] valueForKey:#"label"]];
}
and reloads your tableview.
Hi I have the following json that i need to parse, however, I'm struggling to parse the inner array. What I have currently just prints each of the inner arrays but I'd like to print say each title and add the titles to an array. Thank you for any help!
JSON
{"nodes":[{
"node":{
"nid":"1420857",
"title":"Title 1",
"votes":"182",
"popular":"True",
"teaser":"Teaser 1"
}},
{"node":{
"nid":"1186152",
"title":"Title 2",
"votes":"140",
"popular":"True",
"teaser":"Teaser 2"
}},
{"node":{
"nid":"299856",
"title":"Title 3",
"votes":"136",
"popular":"True",
"teaser":"Teaser 3"
}}
]}
Json Parser
NSError *error = nil;
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.somefilename.json"]];
if (jsonData) {
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(#"error is %#", [error localizedDescription]);
return;
}
NSArray *keys = [jsonObjects allKeys];
for (NSString *key in keys) {
NSLog(#"%#", [jsonObjects objectForKey:key]);
}
} else {
// Handle Error
}
Just typecast it:
NSArray *nodes = (NSArray*)[jsonObjects objectForKey:#"nodes"];
for (NSDictionary *node in nodes){
// do stuff...
}
Methods that return id (like -[objectForKey:], and -[objectAtIndex:]) can return any objective-c object. You'll need to know ahead of time what to typecast it into to perform the appropriate operations on it. JSON is converted to the NSObject equivalents:
object -> NSDictionary
array -> NSArray
string -> NSString
number -> NSNumber
boolean -> NSNumber
float -> NSNumber
null -> NSNull
To differentiate between the various NSNumbers, you'll have to call the appropriate type method: -[intValue], -[boolValue], -[floatValue]. Check out the NSNumber docs for more info.
You can use my method for json parsing,
Parse Method:
-(void)jsonDeserialize:(NSString *)key fromDict:(id)content completionHandler:(void (^) (id parsedData, NSDictionary *fromDict))completionHandler{
if (key==nil && content ==nil) {
completionHandler(nil,nil);
}
if ([content isKindOfClass:[NSArray class]]) {
for (NSDictionary *obj in content) {
[self jsonDeserialize:key fromDict:obj completionHandler:completionHandler];
}
}
if ([content isKindOfClass:[NSDictionary class]]) {
id result = [content objectForKey:key];
if ([result isKindOfClass:[NSNull class]] || result == nil) {
NSDictionary *temp = (NSDictionary *)content;
NSArray *keys = [temp allKeys];
for (NSString *ikey in keys) {
[self jsonDeserialize:key fromDict:[content objectForKey:ikey] completionHandler:completionHandler];
}
}else{
completionHandler(result,content);
}
}
}
Method Call:
NSData *content = [NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:#"Sample" ofType:#"json"]];
NSError *error;
//to get serialized json data...
id dictionary = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:&error];
//get data for key called GetInfo
[self jsonDeserialize:#"GetInfo" fromDict:dictionary completionHandler:^(id parsedData, NSDictionary *fromDict) {
NSLog(#"%# - %#",parsedData,fromDict);
}];