I'm trying to pull in the first url of a tweet using -objectForKey:, and I was wondering how I can pull in the expanded url in 1 go.
Here's the json:
"entities":{
"hashtags":[
],
"symbols":[
],
"urls":[
{
"url":"http:\/\/t.co\/example",
"expanded_url":"http:\/\/example.com\/hi",
"display_url":"example.com\/hi",
"indices":[
46,
68
]
}
],
"user_mentions":[
]
},
This is what I tried: NSLog(#"URL FOUND: %#", [JSON objectForKey:#"entities/urls/expanded_url"]);
but I got (null).
This code will be help for you
NSArray *urls = [[JSON objectForKey:#"entities"] objectForKey:#"urls"];
NSString *url = [[urls objectAtIndex:0] objectForKey:#"url"];
NSLog(#"%#",url);
"urls":[
{
"url":"http:\/\/t.co\/example",
"expanded_url":"http:\/\/example.com\/hi",
"display_url":"example.com\/hi",
"indices":[
46,
68
]
}
],
Here, value of urls is an array, so you should use path like entities/urls[0]/expanded_url
Update:
I don't know which JSON decode library you use.
Take famous JSONKit(https://github.com/johnezang/JSONKit) as an example:
NSString *str = #"{\"entities\":{\"urls\":[{\"url\":\"http://t.co/example\"}]}}";
NSDictionary *dict = [str objectFromJSONString];
NSLog(#"URL: %#",dict[#"entities"][#"urls"][0][#"url"]);
Related
I want to send below JSON parameter in an API call, but the string of contacts array which is used below is confusing and I'm unable to form it in iOS. Below is the working JSON parameter tested in Rest client. How to form a similar pattern of string containing an array of contacts in iOS?
Working JSON Parameter,
{
"contacts": "[\"5555228243\",\"919677012480\"]",
"phno": "919791871448",
"device": "iphone",
"key": "key",
"name": "Logunath Subramaniyan",
"files": "files"
}
My code below for conversion,
NSMutableDictionary *reqData = [[NSMutableDictionary alloc]init];
[reqData setObject:[FMCoredDataUtility fetchDetailForKey:kmobileNumber] forKey:#"phno"];
[reqData setObject:[FMCoredDataUtility fetchUserNameForKey:kuserName ]forKey:#"name"];
[reqData setObject:#"iphone" forKey:#"device"];
[reqData setObject:#"key" forKey:#"key"];
[reqData setObject:[self getMobileContacts ] forKey:#"contacts"];
[reqData setObject:#"files" forKey:#"files"];
-(NSArray*)getMobileContacts{
contactNumbers = [addUtility getContactNumbers];
for ( int i = 0; i < [contactNumbers count]; i++) {
[filteredContacts addObject:[[[contactNumbers objectAtIndex:i] componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:#""]];
}
return filteredContacts;
}
Framed error JSON parameter,
{
"contacts": [
"5555228243",
"5554787672",
"4085555270",
"4085553514",
"5556106679",
"5557664823",
"7075551854",
"8885555512",
"8885551212",
"5555648583",
"4155553695",
"919677012480"
],
"phno": "919791871448",
"device": "iphone",
"key": "key",
"name": "Logunath Subramaniyan",
"files": "files"
}
and error I'm getting in console is,
value __NSCFConstantString *
#"JSON text did not start with array or object and option to allow fragments not set."
0x000000010cf2ed50
Here is a way in which you can convert your ios array to JSON string
NSArray *contactsArray = [self getMobileContacts ];//This will be your contacts array
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[reqData setObject:jsonString forKey:#"contacts"];
I am trying to parse the following json into my iOS code.
{
"test": [
{
"id": "21",
"lat": "53.343377977116916",
"long": "-6.2587738037109375",
"address": "R138, Dublin, Ireland",
"name": "td56",
"distance": "0.5246239738790947"
},
{
"id": "11",
"lat": "53.343377977116916",
"long": "-6.245641708374023",
"address": "68-130 Pearse Street, Dublin, Ireland",
"name": "test1",
"distance": "0.632357483022306"
}
]
}
I am able to view the full json in my logs with the following code:
NSURL *blogURL = [NSURL URLWithString:#"URLHERE"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *test = [dataDictionary objectForKey:#"test"];
NSLog(#"%#",dataDictionary);
if I change data dictionary to test in the log, I can display after the test root in my json , but if I try setup arrays to view, let's say the ID, the entire app will crash.
Could someone direct me in the right way to, let's say, display all the names in the NSLog? Each method I've tried has resulted in the application crashing.
Test is an array:
NSArray *test = [dataDictionary objectForKey:#"test"];
NSLog(#"test =%#", test);
for(NSDictionary *coordinates in test){
NSLog(#"id = %#", coordinates[#"id"]);
NSLog(#"lat = %#", coordinates[#"lat"]);
NSLog(#"long = %#", coordinates[#"long"]);
}
NSArray *array = [dataDictionary valueForKey:#"test"];
for(int i = 0; i < array.count; i++){
NSLog(#"%#", [array[i] valueForKey:#"name"]);
}
like that u can get NSLog whatever key you want
for id
NSLog(#"%#", [array[i] valueForKey:#"id"]);
for lat
NSLog(#"%#", [array[i] valueForKey:#"lat"]);
and so on.....
Happy coding
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"];
I have two classes that define Video and Cue objects. I get my data through an JSON API. The backend is written in Rails and has a one-to-many relationship between Video and Cues.
The data I get is structured like this:
{ "true":
[
{
"id" : 3,
"title" : "My Title"
[
{ "cues":
[
{
"id": 117,
"time" : "12.81",
"video_id" : 3
},
{
"id": 118,
"time" : "14.34",
"video_id" : 3
}
]
}
]
}
]
}
I have a method in Video.m that gets the JSON array, puts it in a dictionary and converts the dictionary to an array of Video objects.
+(id) getVideos {
NSURL *videoURL = [NSURL URLWithString:#"http://localhost:3000/myEndPoint"];
NSData *jsonData = [NSData dataWithContentsOfURL:videoURL];
NSError *error = nil;
NSDictionary *videoDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSMutableArray *videos = [NSMutableArray array];
for (NSDictionary *dict in videoDictionary[#"true"]) {
NSString *title = [dict objectForKey:#"title"];
Video *newVideo = [[Video alloc] initWithTitle:title];
[videos addObject: newVideo];
}
return videos;
}
How should I format the cues so that I can get specific cues from a Video, like in a relational sort of way if possible, if not then just the best practise. In Rails it would be video.cues. Can I do this in Objective C?
Would be perfect if I could end up having the ability to do something like:
Cue *currentCue = video.cues[0];
Add a property to your Video class: NSArray *cues. And change your init method to initWithTitle:(NSString*)title andCues:(NSArray*)cues. That way you'll be able to do exactly that: video.cues[0]
I'm new to ios development. Now I get a JSON file from server.
I use NSDictionary to get objects. When I debug, I could get "name", "address" values.
But I don't know how can I get all "dish" elements from "recommendation" Object? In java development, I know recommendation is an object, and "dish" is an array element. But I don't know what happen in ios.
{
"results": [
{
"name": "ollise",
"address": "columbia university",
"geo": [
{
"coordinates": 40
},
{
"coordinates": 70
}
],
"logo": "http:\/\/a0.twimg.com\/profile_images\/3159758591\/1548f0b16181c0ea890c71b3a55653f7_normal.jpeg",
"recommendation": [
{
"dish": "dish1"
},
{
"dish": "dish2"
}
],
}
]
}
By the way, in JSON, I store URL of an image in "logo", but I cannot get the value when debugging. Should I use some special format?
[Restaurant setname:[Dict objectForKey:#"name"]] // I could get name
[Restaurant setlogo:[Dict objectForKey:#"logo"]] // I can get nothing!
This is the way to do it
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:yourData options:NSJSONReadingMutableLeaves error:nil];
NSDictionary *results = [[response objectForKey:#"results"] objectAtIndex:0];
NSString *name = [response objectForKey:#"name"];
//... get other objects
NSArray *recommendation = [results objectForKey:#"recommendation"];
NSDictionary *recommendation1 = [recommendation objectAtIndex:0];
NSDictionary *recommendation2 = [recommendation objectAtIndex:1];
NSString *dish = [recommendation1 objectForKey#"dish"];
NSString *dish1 = [recommendation2 objectForKey#"dish"];
[Restaurant setname:name];
NSString *logo = [results objectForKey:#"logo"];
[Restaurant setlogo:logo];
The results is the same dictionary as the one in the JSON. Treat anything with braces ({}) as an NSDictionary and brackets ([]) as an NSArray. dish is not an array element, it is a key in a dictionary that is an array element.