I know My question may be lengthy, but I want to share my experience please help me out with an explaination. I am getting a huge Json response from server, and I am storing it into a Dictionary.when I am printing the Dictionary it is showing (null).Can anybody please explain why it is happening like that?
After a little research I am saving the huge Json response to a file and I am able to read the Json from that file.Firstly it worked fine but now I am getting this error
Error Domain=NSCocoaErrorDomain Code=3840 "Unable to convert data
to string around character 1070." UserInfo={NSDebugDescription=Unable
to convert data to string around character 1070.}
This is how I am writing json to a file
-(void)writeJsonDatatoFile:(NSData*)jsonData
{
NSError *errorWriting;
NSString *dest=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)[0] stringByAppendingPathComponent:#"file.json"];
[jsonData writeToFile:dest atomically:YES];
}
This is how I am reading json from file
-(void*)readJsonDataFromFile
{
NSString *source=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)[0] stringByAppendingPathComponent:#"file.json"];
NSError *error;
NSError *error1;
NSData *data=[NSData dataWithContentsOfFile:source options:kNilOptions error:&error1];
NSLog(#"Reading Error--%#",error1);
NSDictionary *dataDict=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"json Data From File--%#-%#",dataDict,error);
}
Related
I m using AFNetworking 2.0 in my iOS application. it's working fine at every stage. I stuck in one problem that how to post smiley with text to update status using Afnetworking. Please help me out if anyone had done this.
"\ud83d\ude04" is the JSON Unicode escape sequence for U+D83D U+DE04, which is the "surrogate pair" for the Unicode U+1F604 (SMILING FACE WITH OPEN MOUTH AND SMILING EYES).
But NSJSONSerialization decodes this correctly, as can be seen in the following example:
const char *jsonString = "{ \"emoji\": \"\\ud83d\\ude04\" }";
NSLog(#"JSON: %s", jsonString);
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.myLabel.text = [jsonDict objectForKey:#"emoji"];
NSLog(#"Emoji: %#", self.myLabel.text);
Output:
JSON: { "emoji": "\ud83d\ude04" }
Emoji: 😄
After testing, I can only get [NSJSONSerialization isValidJSONObject:] to return a positive on JSON data that I have already parsed with [NSJSONSerialization JSONObjectWithData:options:error:].
According to the official documentation:
isValidJSONObject returns a Boolean value that indicates whether a given object can be
converted to JSON data.
However, despite the fact that the objects I am attempting to convert from JSON to a NSDictionary convert fine, isValidJSONObject returns NO.
Here is my code:
NSURL * url=[NSURL URLWithString:urlString];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error=[[NSError alloc] init];
NSMutableDictionary * dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if([NSJSONSerialization isValidJSONObject:data]){
NSLog(#"data is JSON");
}else{
NSLog(#"data is not JSON");
}
if([NSJSONSerialization isValidJSONObject:dict]){
NSLog(#"dict is JSON");
}else{
NSLog(#"dict is not JSON");
}
NSLog(#"%#",dict);
My log contains the following:
data is not JSON
dict is JSON
and then the output of dict, which at this point is a huge NSMutableDictionary object. No errors are generated when running this code, but isValidJSONObject seems to be returning the wrong value when run on data.
How can I get isValidJSONObject to work as expected?
isValidJSONObject tests if a JSON object (a NSDictionary or NSArray) can be successfully
converted to JSON data.
It is not for testing if an NSData object contains valid JSON data. To test for valid
JSON data you just call
[NSJSONSerialization JSONObjectWithData:data ...]
and check if the return value is nil or not.
I am trying to convert a string into a json object and am unsure why this is not working. When I nslog the output I am told that urldata is not valid for json serialization however when looking at the string it looks to me like valid json. I have also tried encoding it to an utf8 however it still won't serialize. Am I missing something here? - Note unnecessary code omitted from post.
Get request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
NSDictionary *tempDict = [NSDictionary alloc];
Parsing
if ([NSJSONSerialization isValidJSONObject:urlData] ) {
NSLog(#"is valid");
tempDict = [NSJSONSerialization JSONObjectWithData:urlData kniloptions error:&error];
}
NSLog(#"is not valid");
Definition:
isValidJSONObject:
Returns a Boolean value that indicates whether a given object can be converted to JSON data.
As you are already mentioning in your question, isValidJSONObject
returns a Boolean value that indicates whether a given object can be
converted to JSON data
In your case, you don't want to create JSON data, but instead create a dictionary out of JSON data. :
tempDict = [NSJSONSerialization JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
if (!tempDict) {
NSLog(#"Error parsing JSON: %#", error);
}
I am allowing for application data (it's a Mac app on 10.7) to be exported as an XML file, and one field I would like to be able to export/import to/from XML is an NSData field. What would be the correct/accepted way of doing this? Should I convert to base64 and write that string to XML?
I would prefer not to roll my own solution, using a category, as the accepted answer to the linked question does (linking to Matt Gallagher's solution).
Update
I just discovered the NSPropertyListSerialization class. I got my hopes up, but it only has static serialization methods which return NSData representations.
I realized (as my updated alluded to) that I could use the NSPropertyListSerialization class, since the NSData returned by -dataWithPropertyList:format:options:error: is just a UTF-8 string. This is what I'm using to serialize:
NSData *data = value;
NSError *error = nil;
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:data
format:NSPropertyListXMLFormat_v1_0
options:0
error:&error];
if (error) {
NSLog(#"Error serializing data to plist XML: %#", error);
} else {
NSString *plistString = [[NSString alloc] initWithData:plistData encoding:NSUTF8StringEncoding];
NSXMLElement *dataElement = [NSXMLElement elementWithName:field
stringValue:plistString];
}
And deserialize:
NSData *plistData = [element.stringValue dataUsingEncoding:NSUTF8StringEncoding];
NSData *originalData = [NSPropertyListSerialization propertyListWithData:plistData
options:NSPropertyListImmutable
format:NULL
error:&error];
if (error) {
NSLog(#"Error deserializing data from plist XML: %#", error);
} else {
value = originalData;
}
I use the following code to create a JSON file.
// Some data in keys and vals.
NSDictionary* dictionary = [NSDictionary dictionaryWithObjects:vals forKeys:keys];
NSError* writeError = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
options:NSJSONWritingPrettyPrinted error:&writeError];
NSString* path = #"json.txt";
[jsonData writeToFile:path atomically:YES];
How can I output a JSONP file? Is there a Cocoa framework I can use?
Update: In the meantime, I used a quick-and-dirty solution: I read in the JSON file just written before to the disc and add the missing JSONP-function to the string. Then, I write the file a second time. I think that's not worth being the answer to my question. So I will leave this question open to a smarter solution.
You could convert the JSON data to a string, wrap it in your function call and then write it to a file. Example:
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
options:NSJSONWritingPrettyPrinted
error:NULL];
NSMutableString *jsonString = [[[NSMutableString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding] autorelease];
[jsonString insertString:#"functionCall(" atIndex:0];
[jsonString appendString:#");"];
[jsonString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
(I'm using a mutable string here for better memory efficiency.)
I don't know objective-c or Cocoa. (I use python on MacOS to create JSNOP responses), but it's a simple thing to do.
The basic idea is to wrap the JSON data in a javascript function call:
functionCall({"Name": "Foo", "Id" : 1234, "Rank": 7});
The tricky part is that the function name, "functionCall", is set by the browser and AFAIK the name of that query parameter is not standardized. jQuery uses jsonCallback. Other's use json or callback. So the request url must be checked for that callback name and that function name must be used to wrap the json data.