hi im using jsonkit to deserialize json kit data. this is the code i use.
NSString * strResult = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
nslog(#"strresult");
NSDictionary *deserializedData = [strResult objectFromJSONString];
nslog(#"result");
o/p:
"data": {
"translations": [
{
"translatedText": "hello"
}
]
}
}
result {
data = {
translations = (
{
translatedText = "\U091c\U093e\U0928\U093e";
}
);
};
}
what is the problem????? thanks in advance
Try to use http://code.google.com/p/json-framework/.
Your code will look like this. And you need to include #import "JSON.h"
NSString * strResult = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"strresult");
NSDictionary *deserializedData = [strResult JSONValue];
I think the problem is from string encoding.
Related
I am parsing an itunes rss feed with JSON but I have run into a problem. The following code is running properly for one the movieName output but I still don't get the movieSummary output.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
feed = [allDataDictionary objectForKey:#"feed"];
arrayOfEntry = [feed objectForKey:#"entry"];
for (NSDictionary *dictionTitle in arrayOfEntry) {
NSDictionary *title = [dictionTitle objectForKey:#"title"];
NSString *labelTitle = [title objectForKey:#"label"];
[arrayLable addObject:labelTitle];
NSDictionary *summary = [dictionTitle objectForKey:#"summary"];
NSString *labelSummary = [summary objectForKey:#"label"];
[arraySummary addObject:labelSummary];
}
movieName.text = [arrayLable objectAtIndex:0];
movieSummary.text = [arraySummary objectAtIndex:0]; //This is not displaying
}
Here is the link that I am parsing: http://itunes.apple.com/us/rss/topmovies/limit=300/json
I run into this situation a lot. I use something like this. Replace your code
NSString *labelTitle = [title objectForKey:#"label"];
[arrayLable addObject:labelTitle];
with
NSString * labelTitle = [ [ title objectForKey:#"label" ] ifNullThenNil ] ;
[ arrayLabel addObject:labelTitle ? labelTitle : #"" ] ; // you could also use #"<unknown>" or similar instead of #""
where -ifNullThenNil is provided via category:
#implementation NSObject (IfNullThenNil)
-(id)ifNullThenNil { return self ; }
#end
#implementation NSNull (IfNullThenNil)
-(id)ifNullThenNil { return nil ; }
#end
The problem was that when I was adding the strings to the Array that it sometimes contained NULL's thus the following code helped me out
if ([[arrayName objectAtIndex:0] isKindOfClass:[NSNull class]]) {
labelName.text = #"This is NULL";
} else {
[arrayName addObject:labelName];
}
if ([[arraySummary objectAtIndex:0] isKindOfClass:[NSNull class]]) {
labelSummary.text = #"This is NULL";
} else {
[arraySummary addObject:labelSummary];
}
I have JSON like this:
[{"ID" : "351", "Name" : "Cam123 ", "camIP" : "xxx.xxx.xxx.xxx",
"Username" : "admin", "Password" : "damin", "isSupportPin" : "1" },
{"ID" : "352", "Name" : "Cam122 ", "camIP" : "xxx.xxx.xxx.xxx",
"Username" : "admin", "Password" : "damin", "isSupportPin" : "0" }
]
I want to get isSupportPin with result: 1 or 0.
if (x == 1)
{
mybutton.enabled = TRUE;
}
else
{
mybutton.enabled = FALSE;
}
How I can do it?
Assuming you have an NSData object with this data in it:
// Your JSON is an array, so I'm assuming you already know
// this and know which element you need. For the purpose
// of this example, we'll assume you want the first element
NSData* jsonData = /* assume this is your data from somewhere */
NSError* error = nil;
NSArray* array = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if( !array ) {
// there was an error with the structure of the JSON data...
}
if( [array count] > 0 ) {
// we got our data in Foundation classes now...
NSDictionary* elementData = array[0]; // pick the correct element
// Now, extract the 'isSupportPin' attribute
NSNumber* isSupportPin = elementData[#"isSupportPin"];
// Enable the button per this item
[mybutton setEnabled:[isSupportPin boolValue]];
} else {
// Valid JSON data, but no elements... do something useful
}
The above example code snippet assumes you know which element you want to read (I guess these are user lines or something) and that you know what the JSON attribute names are (e.g., if isSupportPin isn't actually defined in the JSON object returned in that array, it will simply return nil, which will always evaluate to NO when you send it -boolValue).
Finally, the above code is written for ARC and requires Xcode 4.5 or Clang 4.1 and a deployment target of iOS 5.0. If you're not using ARC, building with a legacy version of Xcode, or targeting something earlier than 5.0, you'll have to adjust the code.
Here what you have is an NSArray of NSDictionarys. So using SBJSON library you could do as following
SBJsonParser *parser = [SBJsonParser alloc] init];
NSArray *data = [parser objectFromString:youJson];
for (NSDictionary *d in data)
{
NSString *value = [d objectForKey:#"Name"];
}
The library can be found at http://stig.github.com/json-framework/
Follow the below link that my help you.
http://www.xprogress.com/post-44-how-to-parse-json-files-on-iphone-in-objective-c-into-nsarray-and-nsdictionary/
If you want to get data or Dictionary fron JSONData then use bellow code..
NSString *responseString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSArray *resultsArray = [responseString JSONValue];
for(NSDictionary *item in resultsArray)
{
NSDictionary *project = [item objectForKey:#"result"];//use your key name insted of result
NSLog(#"%#",project);
}
and also download JSON Library and tutorial from below link...
http://mobileorchard.com/tutorial-json-over-http-on-the-iphone/
I get the following NSDictionary when I parse a JSON response from my server:
(
{
fromUname = Ben;
id = ci2n9awef7tm7e142sx;
message = hi;
read = 1;
subject = hi;
time = 1316513972;
toUname = Jill;
},
{
fromUname = Eamorr;
id = asdf98s14u7tm7e142sx;
message = asdf;
read = 0;
subject = asdf;
time = 1316513322;
toUname = Jack;
}
)
I'm really struggling to extract the two subjects.
Here's what I've coded sofar (incomplete...):
...
SBJsonParser *parser=[[SBJsonParser alloc]init];
NSDictionary *obj=[parser objectWithString:[request responseString] error:nil];
NSLog(#"%#",obj);
NSLog(#"%d",[obj count]);
for(int i=0;i<[obj count];i++){
NSDictionary *message=[obj objectForKey:];
NSLog(#"%#",[message objectForKey:#"subject"]); //I'm stuck...
}
...
Can anyone give me some efficient way of extracting the subjects?
Many thanks in advance,
Its actually an NSArray of NSDictionaries. So to get the information, loop through the array and get the dictionary:
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *obj = [parser objectWithString:[request responseString] error:nil];
NSLog(#"%# : %d",obj, [obj count]);
for (NSDictionary *dict in obj) {
NSLog(#"%#", [dict objectForKey:#"subject"]);
}
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.