Parsing JSON which contains html data - html

I want to parse json data which contains html but there is a problem
I made a parser with this lines but always I got this error: The operation couldn’t be completed. (Cocoa error 3840.)
NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSASCIIStringEncoding];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingMutableContainers error:&error];

You need to fix the incoming JSON object. You will need to encode that HTML in your web-service (whatever that may be). You should be able to see the issue when you run your JSON through a validator like JSONViewer or JSONLint.

Related

NSJSONSerialization not handling negative integers

I’m trying to parse an JSON file into an NSArray and it all works well for positive numbers. However all the negative integers in that JSON file produce high numbers like “[11] __NSCFNumber * (long)72057594037927933”. How can i get that to work?
Here is my JSON file:
[0,1,2,3,4,5,6,7,8,9,10,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11]
and here the code:
NSError* error;
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://some/json/file.json"]];
NSMutableArray* array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
Xcode doesn't always print nice values into the Debug area of the Xcode (where live values for the context appear).
I dropped your code into my own project and when I step through each line, I do see the "eachNumber __NSCFNumber * (long)72057594037927934 {0xbfffffffffffffe3} bits, but if I try print out the values of the array into the console, you'll see the correct "-2" result.
Try it yourself. I added in these lines right after yours:
NSMutableArray* array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"array is %#", array);
for(id eachNumber in array)
{
NSLog(#"eachNumber is %#", eachNumber);
}

Converting NSString to NSData for use in XCODE

I am getting data from the Yummly API and I would like to use it as though it were serialized JSON data. However, it is currently a string, and I cannot figure out how to turn it to data correctly. The code is as following:
NSString *searchParameters = #"basil"; //should be from text box
//NSError *error1 = nil;
NSString *searchURLName = [#"http://api.yummly.com/v1/api/recipes?_app_id=myAPIId&_app_key=myAPIkey&" stringByAppendingString:searchParameters];
NSURL *searchURL = [NSURL URLWithString:searchURLName];
NSString *searchResults = [NSString stringWithContentsOfURL:searchURL encoding:NSUTF8StringEncoding error:nil];
// Here, the search results are formatted just like a normal JSON file,
// For example:
/* [
"totalMatchCount":777306,
"facetCounts":{}
]
*/
// however it is a string, so I tried to convert it to data
NSData *URLData = [searchResults dataUsingEncoding:NSUTF8StringEncoding];
URLData = [URLData subdataWithRange:NSMakeRange(0, [URLData length] - 1)];
_searchArray = [NSJSONSerialization JSONObjectWithData:URLData options:NSJSONReadingMutableContainers error:nil];
Somewhere over the last four lines, it didn't do what it was supposed to and there is no data in the data object. Any advice or quick hints in the right direction are much appreciated! Thank you1
Look at the error being returned from the NSJSONSerialization object like
NSError *error;
_searchArray = [NSJSONSerialization JSONObjectWithData:URLData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#", error);
This might give you a hint of what's wrong. This should work though.
And why exactly are you doing URLData = [URLData subdataWithRange:NSMakeRange(0, [URLData length] - 1)];? You don't need to copy the data, if that's why you're doing that.
Plus, it seems like you're assuming to get an array as the top level object (judging by
/* [
"totalMatchCount":777306,
"facetCounts":{}
]
*/
but this is a dictionary. Basically you probably want a dictionary, not array. This it should be
/* {
"totalMatchCount":777306,
"facetCounts":{}
}
*/
But the error getting returned will tell you that.
It looks like you're over-complicating things a bit. You do not need to bring in this data as an NSString at all. Instead, just bring it in as NSData and hand that to the parser.
Try:
NSString *searchParameters = #"basil"; //should be from text box
NSString *searchURLName = [#"http://api.yummly.com/v1/api/recipes?_app_id=myAPIId&_app_key=myAPIkey&" stringByAppendingString:searchParameters];
NSURL *searchURL = [NSURL URLWithString:searchURLName];
NSData *URLData = [NSData dataWithContentsOfURL:searchURL];
_searchArray = [NSJSONSerialization JSONObjectWithData:URLData options:NSJSONReadingMutableContainers error:nil];
Note that you'll want to verify that the parsed JSON object is indeed an array as expected, and is not/does not contain [NSNull null].

How to get the image from the base64encodedstring ?

I am using base64encoding for sending an UIImage to the server and then on the other end i am getting it back, converting the base64encodedstring in to NSData then trying to get my image back on an UIImageView.
Everything working fine sending the Base64encodedString and receiving it but when i am converting the NSData back in to UIImage it is throwing the following exception
-[__NSArrayI dataUsingEncoding:allowLossyConversion:] exception is comming with Base64 encoding
this is the code i am using for posting the image:
img=mainImage.image;
NSData *imgdata=UIImagePNGRepresentation(img);
NSString *imgstring=[imgdata base64EncodedString];
NSString *post =[[NSString alloc] initWithFormat:#"gid=%#&image=%#",[lblgid text],imgstring];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://www.abcd/updategameimage.php"];
And following is the code at receiving end
NSString *imgStr=[abc valueForKey:#"image"];
NSLog(#"%#",imgStr);
NSData *imgdata=[NSData dataWithBase64EncodedString:imgStr];
imge = [UIImage imageWithData:imgdata];
[imgview setImage:imge];
Here abc is NSMutableArray
Are you sure abc is a mutableArray?
Because you are sending it a valueForKey: method. This is a KVC method implemented by NSObject and it doesn't make sense to send it this message.
If you meant to send it the objectForKey: method instead - then that would be a message that you send to dictionaries, not arrays.
And, the error that you are getting:
-[__NSArrayI dataUsingEncoding:allowLossyConversion:] exception is comming with Base64 encoding
is telling you that an NSArray does not respond to dataUsingEncoding:allowsLossyConversion: messages - which is a method for NSString objects.
I think you are getting confused with your object types and need to get a better handle on what is what.

ios5: Sending JSON data from the iPhone to REST using POST

I am trying to send data in the JSON format to the REST api. When sending a parameter the web service does not return any data but instead gives the following error:Error parsing JSON: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)
This is because the parameter cannot be read by the web service.
But if I add this parameter directly to the URL the correct results are returned Eg:http://localhost:8080/de.vogella.jersey.final/rest/notes/63056
The following is the code for sending the parameters:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://localhost:8080/de.vogella.jersey.final/rest/notes/"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSString *postString = #"{\"notes\":\"63056\"}";
NSLog(#"Request: %#", postString);
// NSString *postString = #"";
[request setValue:[NSString stringWithFormat:#"%d",[postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSLog(#"Return Data%#",returnData);
//Getting the task types from the JSON array received
NSMutableArray *jsonArray =[NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
NSLog(#"jsonArray is %#",jsonArray);
taskTypes =[[NSMutableArray alloc]init ];
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#",error);
} else {
for(NSDictionary *taskType in jsonArray) {
[taskTypes addObject:[taskType objectForKey:#"TaskName"]];
}
}
Any suggestions?
Your error "JSON text did not start with array or object and option to allow fragments not set" could mean two things:
You're specifying that you expect the response object to be in JSON format and it is not (for example, this would happen if you're using an AFJSONRequestOperation and the server returns something other than JSON)
Fix: Get a hold of the server code and make sure it returns a valid JSON object
You have not specified that you're okay with receiving something other than JSON
Fix: If you're using AFNetworking, pass in NSJSONReadingAllowFragments to [NSJSONSerialization JSONObjectWithData:options:error:] on your subclass of AFHTTPClient (Shout out to Cocoa error 3840 using JSON (iOS) for this answer).

How to read a JSON file using the NSJSONSerialization Class Reference?

I need to read a JSON file using the NSJSONSerialization Class Reference, and all the examples that I have found about the use of this class read the content from the webpage itself, instead of reading from a JSON file that has been previously created.Anyone knows how to parse from a JSON file using that class? Thanks.
Simple, quick'n'dirty example:
NSString *jsonPath = [[NSBundle mainBundle] pathForResource:#"foobar"
ofType:#"json"];
NSData *data = [NSData dataWithContentsOfFile:jsonPath];
NSError *error = nil;
id json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"JSON: %#", json);