I currently have an JSON API that looks like this:
{
"posts": [
{
"id": 277,
"title": "test title",
"content": "test content",
"attachments": [
{
"url": "http:\/\/www.example.com\/bar-icon-help#2x.png"
}
}
}
I'm trying to use the "url" which is under "attachments". Please take a look at what im doing wrong:
-(void)dataRequestCompletedWithJsonObject.(id)jsonObject
{
NSDictionary *recipeDictionary = (NSDictionary*)jsonObject;
NSArray* recipeArray = (NSArray*)[recipeDictionary objectForKey:#"posts"];
self.recipes = [[NSMutableArray alloc] init];
for (NSDictionary* dic in recipeArray) {
Recipe *recipe = [[Recipe alloc] init];
recipe.name = [dic objectForKey:#"title"];
recipe.thumbNail = [[dic objectForKey:#"attachements"]objectForKey:#"url"];
recipe.twitterShareCount = [[dic objectForKey:#"id"] intValue];
[recipes addObject:recipe];
}
Mainly trying to figure out what i should use instead of this line:
recipe.thumbNail = [[dic objectForKey:#"attachements"]objectForKey:#"url"];
Thanks to anyone who helps!
You have an array of dicts in attachments object.
[[[dic objectForKey:#"attachements"] objectAtIndex:0] objectForKey:#"url"]
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to use NSJSONSerialization
I am testing to use the web service of my website on iphone Application.
The JSON with problem is that:
[
{
"name": "Jason1",
"age": 20
},
{
"name": "Jason2",
"age": 40
},
{
"name": "Jason3",
"age": 60
}
]
And my codes:
NSData *jasonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://localhost:3000/all_personal_information.json"]];
NSDictionary *json = nil;
if (jasonData) {
json = [NSJSONSerialization JSONObjectWithData:jasonData options:kNilOptions error:nil];
}
The code work fine with {"name":"jason","age":20}
and I can get the values by using json[#"name"] and json[#"age"]
But i don't know how to get the value from the JSON with problem.
I tried to use [json enumerateKeysAndObjectsWithOptions] to transverse the dictionary.
But I will get an error:
enumerateKeysAndObjectsWithOptions:usingBlock:]: unrecognized selector sent to instance 0x89b2490
But I can get the full JSON when I Log the [json description] into console.
Take it in an array.. for example
NSData *jasonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://localhost:3000/all_personal_information.json"]];
NSDictionary *json = nil;
if (jasonData) {
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jasonData options:NSJSONReadingMutableContainers error: &e];
}
the array will contain your
{
"name": "Jason1",
"age": 20
}
etc in its individual indexes. when u want to get the values in it, you can use this below method to get the values
NSDictionary *userName = [jsonArray objectAtIndex:1];
NSString *stringName = [userName valueForKey:#"name"];
You're creating a dictionary while you get an array. If you do the following it should work:
id json = nil;
if (jasonData)
{
json = [NSJSONSerialization JSONObjectWithData:jasonData options:kNilOptions error:nil];
}
if ([json isKindOfClass:NSArray.class])
{
for (id personDef in json)
{
if ([personDef isKindOfClass:NSDictionary.class])
{
NSDictionary * dict = (NSDictionary *) moduleDef;
NSString * name = [dict objectForKey:#"name" withClass:NSString.class];
NSLog(#"Person: #%", name);
}
}
}
In here I do some additional checking if the objects are the ones we expect. If this isn't the case you should add (proper) error handling.
it will help you.
NSMutableDictionary *CompaintsAry =[NSJSONSerialization JSONObjectWithData:respo options:kNilOptions error:&error];
NSMutableArray *tempary =[[NSMutableArray alloc]init];
for (int i=0;i < [CompaintsAry count];i++) {
CfResultFatch *rs = [[CfResultFatch alloc] initWithName:[[CompaintsAry obj ectAtIndex:i]objectForKey:#"Name"]
cipd :[[CompaintsAry objectAtIndex:i] objectForKey:#"Age"]];
[tempary addObject:rs];
}
cfComlaintsLists = [[NSMutableArray alloc] initWithArray:tempary];
SelectComplain = [[NSMutableArray alloc] initWithCapacity:[cfComlaintsLists count]];
[chiftab reloadData];
I got this data from my server using JSON:
{
ID = 198;
dtDate = "2012-03-14 00:00:00";
dtTime = "06:00:00";
iPublished = 1;
sProgram = "Devotional Hits";
}
{
ID = 199;
dtDate = "2012-03-14 00:00:00";
dtTime = "07:00:00";
iPublished = 1;
sProgram = "Old Malayalam Hits";
}
{
ID = 200;
dtDate = "2012-03-14 00:00:00";
dtTime = "08:00:00";
iPublished = 1;
sProgram = "Malayalam New Hits";
}
{
ID = 201;
dtDate = "2012-03-14 00:00:00";
dtTime = "09:00:00";
iPublished = 1;
sProgram = "Melody Songs";
}
{
ID = 202;
dtDate = "2012-03-14 00:00:00";
dtTime = "10:00:00";
iPublished = 1;
sProgram = "Jayachandran Hits";
}
{
ID = 203;
dtDate = "2012-03-14 00:00:00";
dtTime = "11:00:00";
iPublished = 1;
sProgram = "Yesudas Hits";
}
{
ID = 204;
dtDate = "2012-03-14 00:00:00";
dtTime = "12:00:00";
iPublished = 1;
sProgram = "Ilayaraja Hits";
}
I need to split this data and store sProgram data into an array.. need help.
I need to split this format and I want sProgram and dtTime separately. What should I do for that. I'm a little bit confused about string formatting.
If you are using < IOS 5, add SBJSON to your project
//in some.m file
#import JSON.h
// Lets say NSString *recievedValue contains your JSON response.
id jsonRep = [receivedValue jsonValue];
if([jsonRep isKindOfClass:[NSArray class]])
{
// returned JSON Value has a array structure.
NSArray *value = (NSArray *)jsonRep;
//You can access values using objectAtIndex: method if you already know the Index of a value, in your case i think each array object is a NSDictionary
if([[value objectAtIndex:0] isKindOfClass:[NSDictionary class]])
{
// returned JSON Value has a key value compliant structure.
NSDictionary *dicValue = (NSDictionary *)[value objectAtIndex:0];
//You can access values using objectForKey: method if you already know the key value, in your case it can be #"sProgram" for example
}
}
else if([jsonRep isKindOfClass:[NSDictionary class]])
{
// returned JSON Value has a key value compliant structure.
NSDictionary *value = (NSDictionary *)jsonRep;
//You can access values using objectForKey: method if you already know the key value, in your case it can be #"sProgram" for example
}
Your JSON is invalid - I recommend that you use this tool to check this before posting about a JSON-related issue in the future.
However, I have corrected your JSON and validated it - it should look like this:
[
{
"ID": 198,
"dtDate": "2012-03-14 00:00:00",
"dtTime": "06:00:00",
"iPublished": 1,
"sProgram": "Devotional Hits"
},
{
"ID": 199,
"dtDate": "2012-03-14 00:00:00",
"dtTime": "07:00:00",
"iPublished": 1,
"sProgram": "Old Malayalam Hits"
},
{
"ID": 200,
"dtDate": "2012-03-14 00:00:00",
"dtTime": "08:00:00",
"iPublished": 1,
"sProgram": "Malayalam New Hits"
},
{
"ID": 201,
"dtDate": "2012-03-14 00:00:00",
"dtTime": "09:00:00",
"iPublished": 1,
"sProgram": "Melody Songs"
},
{
"ID": 202,
"dtDate": "2012-03-14 00:00:00",
"dtTime": "10:00:00",
"iPublished": 1,
"sProgram": "Jayachandran Hits"
},
{
"ID": 203,
"dtDate": "2012-03-14 00:00:00",
"dtTime": "11:00:00",
"iPublished": 1,
"sProgram": "Yesudas Hits"
},
{
"ID": 204,
"dtDate": "2012-03-14 00:00:00",
"dtTime": "12:00:00",
"iPublished": 1,
"sProgram": "Ilayaraja Hits"
}
]
You can then use the json-framework to parse it.
As you asked, here is how you can now obtain all the values of sProgram:
NSMutableArray *programs = [[NSMutableArray alloc] init];
NSArray *data = [json jsonValue];
for (NSDictionary *dict in data) {
[programs addObject:[dict objectForKey:#"sProgram"]];
}
// programs now contains all the values of sProgram
actually i used Stig Brautaset’s JSON library (version 2.2)
- (void)viewDidLoad
{
[super viewDidLoad];
[table reloadData];
NSMutableData *responseData;
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://ganamradio.com/smartphones/date.php"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// Do any additional setup after loading the view from its nib.
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//label.text = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//[responseData release];
dict=[responseString JSONValue];
NSArray *Programs;
NSArray *Time;
Programs=[dict valueForKey:#"sProgram"];
Time=[dict valueForKey:#"dtTime"];
NSLog(#"......%#",Time);
}
so i got the program list in NSArray programs,, is their any problem using like this..?
Im trying to parse a json string using sbjsonparser. Im having trouble converting it to nsdictionary. I've used sbjsonparser in my other classes and they all worked fine. see my code.
-(void)parseJsonString
{
NSLog(#"%#",jsonString);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *dict;
dict = [parser objectWithString:jsonString error:nil];
NSLog(#"%#",dict);
NSDictionary *dict2;
dict2 = [jsonString JSONValue];
NSLog(#"%#",dict2);
[parser release];
}
here's my console output:
2011-08-12 13:56:55.098 EasyQuiz[5446:13603] [{
"q": "Question Testing",
"score": 1,
"c3": "Choice C",
"c2": "Choice B",
"c1": "Choice A",
"rev": 1,
"id": 1,
"c4": "Choice D"
}]
2011-08-12 13:56:55.686 EasyQuiz[5446:13603] (null)
2011-08-12 13:56:56.296 EasyQuiz[5446:13603] -JSONValue failed. Error is: Illegal start
of token []
2011-08-12 13:56:56.297 EasyQuiz[5446:13603] (null)
I checked the string at http://jsonformatter.curiousconcept.com/ and it appears to be valid. what do you think is causing this problem? thanks!
I printed the error in dict = [parser objectWithString:jsonString error:nil]; and it says:
Error Domain=org.brautaset.SBJsonParser.ErrorDomain Code=0 "Illegal start of token []"
UserInfo=0x62eb920 {NSLocalizedDescription=Illegal start of token []}
EDIT
I tried hardcoding the jsonstring like this
NSString *thisJsonString = #"[{\"q\": \"Question Testing\",\"score\": 1, \"c3\": \"Choice C\", \"c2\": \"Choice B\", \"c1\": \"Choice A\", \"rev\": 1, \"id\": 1, \"c4\": \"Choice D\"}]";
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *dict;
dict = [parser objectWithString:thisJsonString error:nil];
NSLog(#"dict %#",dict);
[parser release];
and I got what I want in the console:
dict (
{
c1 = "Choice A";
c2 = "Choice B";
c3 = "Choice C";
c4 = "Choice D";
id = 1;
q = "Question Testing";
rev = 1;
score = 1;
}
)
EDIT
In case you want to know where I get the data. I downloading a zip file from a website using asihttprequest and the this file is extracted using objective-zip and the extracted file is read like this.
NSString *filePath = [[self applicationDocumentsDirectory]
stringByAppendingPathComponent:#"json.zip"];
//Opening zip file for reading...
progressLabel.text = #"Reading file...";
ZipFile *unzipFile= [[ZipFile alloc] initWithFileName:filePath mode:ZipFileModeUnzip];
//Opening first file...
progressLabel.text = #"Opening file...";
[unzipFile goToFirstFileInZip];
ZipReadStream *read1= [unzipFile readCurrentFileInZip];
//Reading from first file's stream...
NSMutableData *data1= [[[NSMutableData alloc] initWithLength:1000000] autorelease];//100MB
int bytesRead1= [read1 readDataWithBuffer:data1];
NSLog(#"bytes: %d",bytesRead1);
if (bytesRead1 > 0) {
progressLabel.text = #"File is good!";
jsonString = [[[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding] autorelease];
//.... more codes follow, but this is how I get jsonString
Your json is an array of one object, so you can't directly parse it to NSDictionary. First parse it to NSArray and then take first object and put it into a NSDictionary
-(void)parseJsonString
{
NSArray *jsonArray = (*NSArray)[jsonString JSONValue];
NSDictionary *jsonDict = [jsonArray objectAtIndex:0];
NSString *q = [jsonDict objectForKey:#"q"];
...
}
objectWithString:error: is having return type id, modify your code as below and let me know.
NSString *str = [NSString stringWithFormat:#"%#", [parser objectWithString:jsonString error:nil]];
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:str,#"response", nil];
NSLog(#"%#",[dict description]);
Currently I am using the following code to parse the JSON link sent. This is how I also send a GET call to the Google Reader API for an upcoming iPhone application of mine.
- (NSArray *)subscriptionList
{
if(!cookies && [cookies count] == 0) {
[self requestSession];
}
NSString * url = #"http://www.google.com/reader/api/0/subscription/list?output=json&client=scroll";
ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
[request setRequestMethod:#"GET"];
[request setRequestCookies:cookies];
[request addRequestHeader:#"Authorization" value:[NSString stringWithFormat:#"GoogleLogin auth=%#", [self auth]]];
[request startSynchronous];
subfeeds = [NSMutableArray array];
// Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
if ([request responseStatusCode] == 200) {
NSData * sixty = [request responseData];
NSString * body = [[NSString alloc] initWithData:sixty encoding:NSUTF8StringEncoding];
if (body) {
NSArray *feeds = [parser objectWithString:body error:nil];
NSLog(#"Array Contents: %#", [feeds valueForKey:#"subscriptions"]);
NSLog(#"Array Count: %d", [feeds count]);
NSDictionary *results = [body JSONValue];
NSArray *ohhai = [results valueForKey:#"subscriptions"];
for (NSDictionary *title in ohhai) {
subTitles = [title objectForKey:#"title"];
NSLog(#"title is: %#",subTitles);
}
}
}
return subfeeds;
[subTitles release];
[parser release];
}
I can successfully parse the JSON using the above code, and it successfully outputs the titles into NSLog. In my RootViewController.m, I call the following to grab this -(NSArray *)subscriptionList.
-(void)viewDidAppear:animated {
GoogleReader * reader = [[GoogleReader alloc] init];
[reader setEmail:gUserString];
[reader setPassword:gPassString];
//feedItems is a NSArray where we store the subscriptionList NSArray
feedItems = [reader subscriptionList];
//NSString *feedTitle = [];
NSLog(#"%#", feedItems);
[reader release];
// the rest of the function
}
The code above successfully works with the credentials entered. As you can see there is also a commented NSString called feedTitle. This is where I want to pull the #"title" from the parsed JSON but I do not know how to call it.
Any help would be greatly appreciated!
This is what the JSON source looks like:
{"subscriptions":
[
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""}
]
}
I'm interested in only the "title" node.
Well, it would help if you added the source JSON but it's quite easy to grasp how SBJSON parses incoming JSON.
Just an example:
{ "myOutDict" : { "key1": "val1" , "key2" : "val2"} }
This JSON String would be parsed so you can access it by using this code
NSDictionary* myOuterdict = [feeds valueForKey:#"myOutDict"]);
NSString* val1 = [myOuterdict valueForKey:#"key1"]);
NSString* val2 = [myOuterdict valueForKey:#"key2"]);
Edit: Checked my personal Google Reader feed:
The JSON looks like this
{
"subscriptions": [{
"id": "feed/http://adambosworth.net/feed/",
"title": "Adam Bosworth's Weblog",
"categories": [],
"sortid": "0B5B845E",
"firstitemmsec": "1243627042599"
},
{
"id": "feed/http://feeds.feedburner.com/zukunftia2",
"title": "Zukunftia",
"categories": [],
"sortid": "FCABF5D4",
"firstitemmsec": "1266748722471"
}]
}
So the corresponding Objective C Code would be:
NSArray* subscriptions= [feeds valueForKey:#"subscriptions"]);
foreach(NSDictionary* item in subscriptions) {
// Do stuff
// NSString* title = [item valueForKey:#"title"]
// NSString* id = [item valueForKey:#"id"]
}
I'm not sure I understand the question. Are you trying to get a title for the feed as a whole, or per-item? Because I can't see a title property for the subscriptions array in the source JSON.
So I've got json-framework up and running on my project, but need help figuring out how to use it to parse this json string:
[
{
"id":"0",
"name":"name",
"info":"This is info",
"tags":
[
{
"id":"36",
"tag":"test tag"
},
{
"id":"37",
"tag":" tag 2"
}
],
"other":"nil"
},
{
"id":"1",
"name":"name",
"info":"This is info",
"tags":
[
{
"id":"36",
"tag":"test tag"
},
{
"id":"37",
"tag":" tag 2"
}
],
"other":"nil"
}
]
Any help and maybe sample code on how to go about this specific type of json would be great. Somehow I can't get it into a dictionary I can read out of. Thanks so much.
The reason why you can't get this string into a dictionary is because it isn't a dictionary, it's an array of dictionaries
You can get the values into an Objective-C object by storing it in an NSArray:
NSArray *objects = (NSArray*) [jsonString JSONValue];
Then, you can loop over those objects that are in the array:
for(NSDictionary *dict in objects) {
NSString *id = (NSString *) [dict objectForKey:#"id"];
NSString *name = (NSString *) [dict objectForKey:#"name"];
NSArray *tags = (NSArray *) [dict objectForKey: #"tags"];
//loop over tags here...
for(NSDictionary *tag in tags) {
NSString *tag_id = (NSString *) [tag objectForKey:#"id"];
NSString *tag_name = (NSString *) [tag objectForKey:#"tag"];
}
//...
}