JSON parsing odd node - ios

I am parsing something like this from this website: http://www.prindlepost.org/?json=1
posts: [
{
....
categories: [],
tags: [],
....
One of the tags within 'post' is this:
author: {
id: 43,
slug: "connergordon_2016",
name: "Conner Gordon",
first_name: "Conner",
last_name: "Gordon",
nickname: "connergordon_2016",
url: "",
description: "Conner is a web and social media intern at the Prindle Institute. A Political Science major from Indiana, Conner's ethical interests lie in memory studies, conflict analysis and the ethics of representation. He also has interests in literature, art and photography."
},
This is how I am parsing the rest successfully:
// convert to JSON
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
// extract specific value...
NSArray *results = [res objectForKey:#"posts"];
for (NSDictionary *result in results)
{
....
// loop through the array of categories
NSArray *categories = [result objectForKey:#"categories"];
for (NSDictionary *category in categories)
{
// ID
NSString *tempIDCategoryString = [category objectForKey:#"id"];
NSInteger *UniqueCategoryID = [tempIDCategoryString intValue];
// slug
NSString *Categoryslug = [category objectForKey:#"slug"];
// title
NSString *Categorytitle = [category objectForKey:#"title"];
// description
NSString *Categorydescription = [category objectForKey:#"description"];
// parent
NSString *Categoryparent = [category objectForKey:#"parent"];
// post_count
NSString *Categorypost_count = [category objectForKey:#"post_count"];
}
// </categories>
}
I have no idea how to parse this author node out of the array of objects within 'post'. Its not an array and it doesn't look like a JSON object to me. I might be wrong though. Help?

Author is a dictionary node.You can try this.
for (NSDictionary *result in results)
{
....
//get the author dictionary
NSDictionary *postDict = [result objectForKey:#"author"];
// loop through the array of categories
NSArray *categories = [result objectForKey:#"categories"];
...
}

Its very much simple...just access it with valueForKey
NSArray *results = [res objectForKey:#"posts"];
[results[#"author"] valueForKey:#"id"];
And you are done

Related

How to retrieve specific value of key in json?

this is my json content.
[
{
"sha":"30eae8a47d0203ac81699d8fc2ab2632de2d0bba",
"commit":{
"author":{
"name":"Madhura Bhave",
"email":"mbhave#pivotal.io",
"date":"2017-03-23T23:14:32Z"
},
"committer":{
"name":"Madhura Bhave",
"email":"mbhave#pivotal.io",
"date":"2017-03-23T23:14:32Z"
},
"message":"Merge branch '1.5.x'",
}
}
]
and this is my main.i just want to retrieve key value from message and name,email,date from committer dictionary.i got stuck how to do that.
NSMutableArray *CommitArray = [[NSMutableArray alloc] init];
for (NSDictionary *CommitDictionary in CommitJson) {
CommitDict *commitDictObj = [[CommitDict alloc] init];
commitDictObj.message = [CommitDictionary objectForKey:#"message"];
for (NSDictionary *CommitterDictionary in [CommitDictionary objectForKey:#"committer"]) {
Committer *author = [[Committer alloc] init];
author.name = [CommitterDictionary objectForKey:#"name"];
author.email = [CommitterDictionary objectForKey:#"email"];
author.date = [CommitterDictionary objectForKey:#"date"];
}
[CommitArray addObject:commitDictObj];
}
for (int i =0 ; i < [CommitArray count] ; i++){
CommitDict *commitDictObj = [CommitArray objectAtIndex:i];
NSLog(#"Commit Message: %#", commitDictObj.message);
}
return 0;
}
}
i try fetch the json and display it value of message,name,email and date.how can i log the value of message, name, email and date?
Your array contains a dictionary, and that dictionary contains the commit dictionary, not the commit dictionary directly. Replace that part of your code:
for (NSDictionary *CommitDictionary in CommitJson) {
CommitDict *commitDictObj = [[CommitDict alloc] init];
With that:
for (NSDictionary *shaCommitDictionary in CommitJson) {
CommitDict *commitDictObj = [[CommitDict alloc] init];
NSDictionary *CommitDictionary = [shaCommitDictionary objectForKey:#"commit"];
(1) Convert JSON to NSDictionary
NSData *jsonData= ... // Assume you got the data already loaded
NSError *error = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
(2) Access the dictionary values (fast enumeration available by now!!
NSString *message = dictionary[#"message"];
NSDictionary *author = dictionary[#"author"];
NSString *name = author[#"author"];
NSString *email = author[#"author"];
NSString *date = author[#"author"];
// OR:
// NSString *name = dictionary[#"author"][#"author"];
// NSString *email = dictionary[#"author"][#"author"];
// NSString *date = dictionary[#"author"][#"author"];
And thats it. I think the tricky thing is to get the JSON Data to the NSDictionary?
See here: https://stackoverflow.com/a/30561781/464016

iOS SBJson request goes bad

I'm trying to parse a JSON feed from my wordpress blog. I've got a custom field I need to use but can't get it to work with SBJson. Here's how my feed looks like (I've stripped the other useless stuff):
{
"status":"ok",
"count":27,
"count_total":2552,
"pages":95,
"posts":[
{
"id":8978,
"type":"post",
"custom_fields":{
"btnNameScrollBlog":[
"<null>"
]
"author-name":[
"John Doe"
]
},
}
I'm trying to get the author's name.
Here's the code I used for getting the feed on iOS:
-(void)downloadRecentPostJson{
[recentPost removeAllObjects];
[previous_total_per_page removeAllObjects];
NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:#"%#/?json=%#",url,methodJson]];
NSData *sa = [NSData dataWithContentsOfURL:urls];
NSString *jsonString = [[NSString alloc] initWithData:sa encoding:NSUTF8StringEncoding];
NSDictionary *result = [jsonString JSONValue];
NSArray* posts = [result objectForKey:#"posts"];
total_page = [[result objectForKey:#"pages"] intValue];
total_post_per_page = [[result objectForKey:#"count"] intValue];
[previous_total_per_page addObject:[result objectForKey:#"count"]];
current_page = 1;
for (NSDictionary *post in posts) {
id custom = [post objectForKey:#"custom_fields"];
id thumbnail = [post objectForKey:#"thumbnail"];
NSString *featuredImage = #"";
if (thumbnail != [NSNull null])
{
featuredImage = (NSString *)thumbnail;
}
else
{
featuredImage = #"0";
}
[recentPost addObject:[NSArray arrayWithObjects:[post objectForKey:#"id"],[post objectForKey:#"title_plain"],[post objectForKey:#"excerpt"],featuredImage,[post objectForKey:#"content"],[post objectForKey:#"date"],[post objectForKey:#"comments"],[post objectForKey:#"comment_status"],[post objectForKey:#"scrollBlogTemplate"],[post objectForKey:#"url"],[post objectForKey:#"specialBtn"],[post objectForKey:#"btnNameScrollBlog"],[post objectForKey:#"latScrollBlog"],[post objectForKey:#"longScrollBlog"],[post objectForKey:#"openWebUrlScrollBlog"],[post objectForKey:#"gallery"], [custom objectForKey:#"author-name"], nil]];
}
I tried setting the custom_fields object as an id: id custom = [post objectForKey:#"custom_fields"];
And then using it to get to the author's name: [custom objectForKey:#"author-name"]
But I get an NSInvalidArgumentException', reason: '-[__NSArrayM rangeOfString:]: unrecognized selector error.
Any suggestions??
What if I try and get the category title from the post?
"categories": [
{
"id": 360,
"slug": "deals",
"title": "Deals",
"description": "",
"parent": 0,
"post_count": 28
}
],
Do I put the categories in an array like this? How do I get the title from that? I tried this and getting the object at index 3, but got an error.
NSArray *cat = [post objectForKey:#"categories"];
'-[__NSArrayM rangeOfString:]: unrecognized selector error. means that you are treating an array as a string. Your code is nearly correct, you just need to get the first item from the array (preferably with a check that the array isn't empty) because
"author-name":[
"John Doe"
]
is an array containing one string. So:
NSArray *names = [custom objectForKey:#"author-name"];
NSString *name = [names firstObject];
NSArray *categories = [custom objectForKey:#"categories"];
NSDictionary *category = [categories firstObject];
NSString *title = [category objectForKey:#"title"];

JSON Parse iOS Array of Dictionaries parsed into array only displays last object in tableview

I have a JSON array of dictionaries that I'm parsing. My problem is where I want to display all the records that fit my required key-value pair (key is name) within the array, I'm only displaying the very last one in my tableview. It's almost 4am and I've been going around in circle since 10pm so any help would be greatly appreciated as I'm overlooking something. Thanks!
NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
self.someArray = [[NSMutableArray alloc]init];
for (NSMutableDictionary *dictionary in jsonDataArray)
{
NSMutableArray* Response_array = [dictionary objectForKey:#"loans"];
NSLog(#"Array: %#", Response_array);
NSDictionary *dict = [Response_array objectAtIndex:0];
NSLog(#"dict is %#",dict);
self.someMutableArray = [dict objectForKey:#"name"];
NSLog(#"what is name %#",self.someMutableArray);
}
and I tried:
NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
for ( int i = 0 ; i < jsonDataArray.count ; i++ )
{
self.someDictionary = [[jsonDataArray objectAtIndex:i] objectForKey:#"loans"];
self.someMutableArray = [self.someDictionary valueForKey:#"name"];
NSLog(#"MutableArray inside is %#", self.someMutableArray);
}
NSLog(#"MutableArray outside is %#",self.someMutableArray);
On my last attempt I moved the location of valueForKey:#"name":
NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
self.someMutableArray = [NSMutableArray array];
for ( int i = 0 ; i < jsonDataArray.count ; i++ )
{
self.someMutableArray = [[jsonDataArray objectAtIndex:i] objectForKey:#"loans"];
}
NSLog(#"someMutableArray outside is %#",self.someMutableArray);
Then in cellForRowAtIndexPath of my tableview, I have:
NSDictionary *dict2 = [self.someMutableArray objectAtIndex:indexPath.row];
NSLog(#"what is dict2 %#", dict2);
cell.textLabel.text = [dict2 valueForKey:#"name"];
Here's the setup of my JSON:
[
-{
id: 285,
name: name 1,
-loans: [
-{
id: 42,
name: "Shark"
}
]
},
-{
id: 286,
name: name 2,
-loans: [
-{
id: 50,
name: "Flipper"
}
]
}
]
Why are you going for a looping when already you have the Array? Just allocate your array with JSON response
NSArray *jsonDataArray = [[NSArray alloc] initWithArray:[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]];
this array will be your datasource so return its count from delegate and in you rowAtIndexPath
NSDictionary *dictObject = [jsonDataArray objectAtIndex:indexPath.row];
cell.textLabel.text = [dictObject valueForKey:#"Shark"];
For custom cell do like
NSDictionary *dictObject = [jsonDataArray objectAtIndex:indexPath.row];
cell.textLabel1.text = [dictObject valueForKey:#"Shark"];
cell.textLabel2.text = [dictObject valueForKey:#"Flipper"];
From my example:
My JSON File:
{
status: "Success",
totalcount: "25",
currentcount: "25",
ticketreplies: [
{
ticket_id: "5348CD97",
subject: "bA==",
posteduser: "10025",
postedby: "Admin (Paul)",
message: "PGRpdj4",
post_id: "75",
posted_on: "23 Apr 2014 12:58 IST",
photo: "10025.jpg"
},
{
ticket_id: "5348F754",
subject: "Y2FsbCBv",
posteduser: "10025",
postedby: "Admin (John)",
message: "PGRpdj4",
post_id: "74",
posted_on: "23 Apr 2014 11:46 IST",
photo: "10025.jpg"
}
]
}
My Implementation:
self.dic_response=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(#"Dictionary: %#",self.dic_response);
NSLog(#"Dictionary: %i",[self.dic_response count]);
NSString usrTicketId=[self.dic_response valueForKey:#"totalcount"];
NSLog(#"Ticket_Id: %#",usrTicketId);
NSArray arrTicketRplys=[self.dic_response valueForKey:#"ticketreplies"];
NSLog(#"Ticket_Id: %#",arrTicketRplys);
for(NSArray *tmpArr1 in arrTicketRplys){
if([[tmpArr1 valueForKey:#"posteduser"] isEqualToString:#"10025"]){
NSString *strPostUserName=[tmpArr1 valueForKey:#"postedby"];
NSLog(#"Posted BY: %#", strPostUserName);
}
}
// Sure, it'll logic work for read specific object keys and values.
// Mainly, these code avoid static values like objectAtIndex:4.
self.dic_response=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
if([self.dic_response valueForKey:#"success"]){
NSMutableArray *resultArray = [NSMutableArray alloc];
for(NSDictionary *tmpArr1 in self.dic_response){
{
[resultArray addObject:tmpArr1];
//this resultArray have whole array value.
}
}
Hope this is helps you
for ( int i = 0 ; i <jsonDataArray.count ; i++ )
{
self.someDictionary = [[jsonDataArray objectAtIndex:i] objectForKey:#"loans"];
[self.someMutableArray addObject:[self.someDictionary valueForKey:#"name"]]
NSLog(#"MutableArray inside is %#", self.someMutableArray);
}
NSLog(#"MutableArray outside is %#",self.someMutableArray);
----------

After convert JSON array to NSDictionary, what should I do?

I need to parse a JSON array in the following format:
[
{
name: "10-701 machine learning",
_id: "52537480b97d2d9117000001",
__v: 0,
ctime: "2013-10-08T02:57:04.977Z"
},
{
name: "15-213 computer systems",
_id: "525616b7807f01fa17000001",
__v: 0,
ctime: "2013-10-10T02:53:43.776Z"
}
]
So after getting the NSData, I transfer it to a NSDictionary:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"%#", dict);
But viewing from the console, I think the dictionary is actually like this:
(
{
"__v" = 0;
"_id" = 52537480b97d2d9117000001;
ctime = "2013-10-08T02:57:04.977Z";
name = "10-701 machine learning";
},
{
"__v" = 0;
"_id" = 525616b7807f01fa17000001;
ctime = "2013-10-10T02:53:43.776Z";
name = "15-213 computer systems";
}
)
What do those parenthesis in the outside mean? How should I further transfer this NSDictionary to an NSArray or an NSMutableArray of some Course objects (what I defined myself, try to represent each element of the JSON array)?
Use this code,
NSArray *array = [NSJSONSerialization JSONObjectWithData: responseData options:NSJSONReadingMutableContainers error:&error];
NSDictionary *dict = [array objectAtIndex:0];
Then you can retrieve the values by following code,
NSString *v = [dict objectForKey:#"__v"];
NSString *id = [dict objectForKey:#"_id"];
NSString *ctime = [dict objectForKey:#"ctime"];
NSString *name = [dict objectForKey:#"name"];
The parenthesis are just the result of NSDictionary output format not being exactly the same thing as how JSON is formatted. Your code still successfully converted the JSON into a NSDictionary object.
I think what you really want, though, is an array of dictionaries. Something like this:
NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *firstObject = [json objectAtIndex:0];
After this, firstObject would contain:
{
"__v" = 0;
"_id" = 52537480b97d2d9117000001;
"ctime" = "2013-10-08T02:57:04.977Z";
"name" = "10-701 machine learning";
}
And you can retrieve the information with objectForKey:
NSString *time = [firstObject objectForKey:#"ctime"];
// time = "2013-10-08T02:57:04.977Z"
Hope that helps.

How can I get the JSON array data from nsstring or byte in xcode 4.2?

I'm trying to get values from nsdata class and doesn't work.
here is my JSON data.
{
"count": 3,
"item": [{
"id": "1",
"latitude": "37.556811",
"longitude": "126.922015",
"imgUrl": "http://175.211.62.15/sample_res/1.jpg",
"found": false
}, {
"id": "3",
"latitude": "37.556203",
"longitude": "126.922629",
"imgUrl": "http://175.211.62.15/sample_res/3.jpg",
"found": false
}, {
"id": "2",
"latitude": "37.556985",
"longitude": "126.92286",
"imgUrl": "http://175.211.62.15/sample_res/2.jpg",
"found": false
}]
}
and here is my code
-(NSDictionary *)getDataFromItemList
{
NSData *dataBody = [[NSData alloc] initWithBytes:buffer length:sizeof(buffer)];
NSDictionary *iTem = [[NSDictionary alloc]init];
iTem = [NSJSONSerialization JSONObjectWithData:dataBody options:NSJSONReadingMutableContainers error:nil];
NSLog(#"id = %#",[iTem objectForKey:#"id"]);
//for Test
output = [[NSString alloc] initWithBytes:buffer length:rangeHeader.length encoding:NSUTF8StringEncoding];
NSLog(#"%#",output);
return iTem;
}
how can I access every value in the JSON? Please help me.
look like this ..
NSString *jsonString = #"your json";
NSData *JSONdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
if (JSONdata != nil) {
//this you need to know json root is NSDictionary or NSArray , you smaple is NSDictionary
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
if (jsonError == nil) {
//every need check value is null or not , json null like ( "count": null )
if (dic == (NSDictionary *)[NSNull null]) {
return nil;
}
//every property you must know , what type is
if ([dic objectForKey:#"count"] != [NSNull null]) {
[self setCount:[[dic objectForKey:#"count"] integerValue]];
}
if ([dic objectForKey:#"item"] != [NSNull null]) {
NSArray *itemArray = [dic objectForKey:#"item"]; // check null if need
for (NSDictionary *itemDic in itemArray){
NSString *_id = [dic objectForKey:#"id"]; // check null if need
NSNumber *found = (NSNumber *)[dic objectForKey:#"found"];
//.....
//.... just Dictionary get key value
}
}
}
}
I did it by using the framework : http://stig.github.com/json-framework/
It is very powerfull and can do incredible stuff !
Here how I use it to extract an item name from an HTTP request :
(where result is the JSO string)
NSString *result = request.responseString;
jsonArray = (NSArray*)[result JSONValue]; /* Convert the response into an array */
NSDictionary *jsonDict = [jsonArray objectAtIndex:0];
/* grabs information and display them in the labels*/
name = [jsonDict objectForKey:#"wine_name"];
Hope this will be helpfull
Looking at your JSON, you are not querying the right object in the object hierarchy. The top object, which you extract correctly, is an NSDictionary. To get at the items array, and the single items, you have to do this.
NSArray *items = [iTem objectForKey:#"item"];
NSArray *filteredArray = [items filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:#"id = %d", 2];
if (filteredArray.count) NSDictionary *item2 = [filteredArray objectAtIndex:0];
Try JSONKit for this. Is is extremely simple to use.
Note sure if this is still relevant, but in iOS 5, apple added reasonable support for JSON. Check out this blog for a small Tutorial
There is no need to import any JSON framework. (+1 if this answer is relevant)

Resources