iOS SBJson request goes bad - ios

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

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

Separate a String By Semicolon

I am using following code to separate a string into multiple strings and getting an error
NSArray *arr = [randomStr componentsSeparatedByString:#";"];
Error:
-[__NSDictionaryM componentsSeparatedByString:]: unrecognized selector sent to instance 0x1758f230
-[__NSDictionaryM componentsSeparatedByString:]: unrecognized selector sent to instance 0x1758f230
This is my Sample Data
NSArray *data = {
{
name = "name1";
address = "RWP";
ID = 0;
},
{
name = "name2";
address = "RWP";
ID = 1;
},
{
name = "name3";
address = "RWP";
ID = 2;
},}
NSString *randomStr = data[0];
What's wrong in my code
You have an array of dictionaries, not strings. There is nothing to split.
You want something like this:
NSDictionary *dict = data[0];
NSString *name = dict[#"name"];
NSString *address = dict[#"address"];
You have to be sure randomStr as a NSString.
You can check like
if ([randomStr isKindOfClass:[NSString Class]]) {
NSArray *arr = [randomStr componentsSeparatedByString:#";"];
}
It sounds like the randomStr variable is an MutableDictionary. Thats why its not working.
here is my Test:
NSString *foo = #"BAR;FOO;VAR";
NSArray *arr = [foo componentsSeparatedByString:#";"];
NSLog(#"%#", arr);
Thise Logs:
BAR,
FOO,
VAR
EDIT:
Dictionary to array:
NSMutableDictionary *dict = #{#"aKey1" :#"BAR",
#"aKey2" :#"FOO",
#"aKey3" :#"VAR"}.mutableCopy;
NSMutableArray *array = [[NSMutableArray alloc] init];
for (NSString *key in dict) {
[array addObject:dict[key]];
}
NSLog(#"%#",array);
This Logs:
BAR,
FOO,
VAR

JSON parsing odd node

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

How to access the my JSON in iOS

I'm newbie in iOS. And I'm having a problem accessing my JSON file that I retrieve in my web app server.
JSON:
{
"content": [
{
"info": [
{
"type": "TEL",
"label": "Call Phone",
"id": "32d7da39-39cc-4319-ab76-e67db9385722"
}
],
"name": "myname",
"title": "myname_title",
"image": "",
}
],
"timestamp": 1370491676,
"error": "SUCCESS"
}
I convert NSData to JSON :
NSMutableDictionary *mydatas =[NSJSONSerialization JSONObjectWithData:urlData options:kNilOptions error:&error];
When I'm using this code to retrieve the name:
NSString *name = [[mydatas objectForKey:#"content"] objectForKey:#"name"];
It terminate the program.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x71e3240'
Include SBJSon Framework from here
NSString *responseString = [[NSString alloc]initWithData: urlData encoding:NSUTF8StringEncoding];
//NSLog(#"%#",responseString);
NSDictionary * mydatas = [responseString JSONValue];
NSString *name = [[mydatas objectForKey:#"content"]objectForKey:#"name"];
content is an NSArray, not an NSDictionary. You need to use NSArray calls to retrieve the item in the array:
// Be sure to check that the array has at least one item or you'll throw an exception
NSArray *contentArray = [mydatas objectForKey:#"content"];
if ( contentArray.count > 0 ) {
NSString *image = [contentArray[0] objectForKey:#"name"];
}
Why you are not using the SBJSON framework . https://github.com/stig/json-framework/.
Then refer following SO question :How to parse JSON into Objective C - SBJSON . This will be easy for you to parse this data.
NSArray *contentArray = [mydatas objectForKey:#"content"];
[contentArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"name of content at index %i is == %#",idx,[obj valueForKey:#"name"]);
}];
By looking at your JSON I can say,
Your mydatas dictionary contains 3 keys which are content, timestamp, error
The object for key content is an array. If you want to retrieve the object for key name you need to do the following
if([[mydatas objectForKey:#"content"] count]>0)
{
NSString *name = [[[mydatas objectForKey:#"content"] objectAtIndex:0]objectForKey:#"name"];
}
This will work.
try like this,
NSString *name = [[[mydatas objectForKey:#"content"] objectAtIndex:0]objectForKey:#"name"];
Try This One
NSMutableDictionary *mydatas =[NSJSONSerialization JSONObjectWithData:urlData options:kNilOptions error:&error];
Save it to Array
NSArray *array = [mydatas objectForKey:#"content"];
for (int i=0; i<[array count]; i++) {
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setValue:[[array objectAtIndex:i] valueForKey:#"info"] forKey:#"info"];
[someArray addObject:dic];
[typeArray addObject:[[dic valueForKey:#"info"] valueForKey:#"type"] valueForKey:#"name"]];
NSString * NameStr = [typeArray objectAtIndex:i];
NSLog(#"String For Name : %#",NameStr);
[dic release];
}
Hope its Work!!!!!!!!!!!

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