How to NSLog NSData JSON response in JSON format? - objective-c

Is there a way I can NSLog JSON response of NSData in JSONformat?
NSLog(#"JSON NSString: %#" ,jsonData);
In this post they are printing NSDictionary,I can convert it to NSDictionary. and this solution returns (null).
How can I NSLog in JSON format?

• What's wrong:
jsonData (as you gave) IS NOT a hexData representing a JSON.
• Quick hack (not viable solution!) to get your JSON to use in your site CodeBeautify:
NSDictionary *dictFromData = [NSKeyedUnarchiver unarchiveObjectWithData:jsonData];
NSData *realJSONData = [NSJSONSerialization dataWithJSONObject:dictFromData options:0 error:nil];
NSString *strFINAL = [[NSString alloc] initWithData:realJSONData encoding:NSUTF8StringEncoding];
NSLog(#"StrFINAL: %#", strFINAL);
Note: Yeah, I bypassed the error parameters, and we shouldn't. With
NSJSONWritingPrettyPrinted instead of 0 in options: parameter, you have a result almost similar to the one of CodeBeautify.
• How did I get there:
Firt, I copy/paste your bump string of NSData with this answer.
That way, I got jsonData as you got.
Then, I tried simply what it should be given your informations:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&errorJSON];
Which didn't work giving the error:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be
completed. (Cocoa error 3840.)" (Invalid value around character 0.)
UserInfo=0x17598540 {NSDebugDescription=Invalid value around character
0.}
But with NSDictionary *dictWithData = [NSKeyedUnarchiver unarchiveObjectWithData:jsonData];, I managed to get the real NSDictionary. But NSKeyedArchiver/NSKeyedUnarchiver are doing something "equivalent" to NSJSONSerialization: it serializes, transforming a NSObject into NSData (and vice-versa). But more powerful: for any kind of object that are NSCoding compliant. Here, since it's originally from a JSON (only NSString, NSNumber, NSArray and NSDictionary objects, and not a custom one), it's working without any more code.
Did you for instance tried to save it into NSUserDefaults and it's not a .plist either (that was also one on my tries, I saved jsonData into memory, and used dictionaryWithContentsOfFile: giving me weird answer, but a important one in the bump of it: ""$class" = "{value = 23}";" which lead me to NSKeyArchiver/NSKeyUnarchiver). I don't know what you did exactly.
• Conclusion:
So clearly, somewhere, you mixed stuff found on the web. You need to rework that. You can't let it like this. There is issue in your code elsewhere. Where did you get jsonData from? What did you do with it?

Code:
NSLog("Formatted JSON : %#" ,[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);

There are different situations. If parsing the JSON data was fine, then you just want to log the result (dictionary or array). If parsing the JSON data failed, and you suspect there is something wrong with the JSON data, then you convert the JSON data to an NSString and log that. And finally, if either conversion to NSString failed, or you look at the NSString and can't find what's wrong with it, then you log the NSData itself to be able to see the bytes. That's useful if someone managed to put control characters or some other nonsense into your JSON data.
The best is to write a method (warning! not for the timid! requires writing code yourself) that takes the NSData, analyses it and prints out the information that you need.

Related

Putting NSData into an NSArray

I have NSData objects storing data (non character / non-ascii). I'm trying to put it into an array without it being interpreted as characters or ascii. I know this question has been asked a few times before, but none of the solutions posted have worked for me in this situation. I'm trying to avoid using property lists, which is what most answers suggested. I already tried converting the NSData to an NSString, then storing the string in the array, but of course it is interpreted as characters after putting it in the string, regardless of the encoding I've used. For example, one of the NSData's contains the value 2c, and when I put it into a string it is interpreted as ,. Does anyone know how I can store the raw data, in its original state, in an NSArray? Maybe by storing the data in user defaults, then somehow storing the defaults in an array? I'm at a loss.
Here is some possibly relevant code:
NSData *receivedData = [bleDevice readData];
NSString *receivedDataString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
[dataArray insertObject:receivedDataString atIndex:0];
When I call:
[dataArray insertObject:receivedDataString atIndex:0];
It will store something like 2c ad a ,.
But, when I try and insert the raw data, like:
[dataArray insertObject:receivedData atIndex:0];
It will simply not store anything. There are no warnings, no errors. I'll NSLog the array and it is null.
[dataArray insertObject:receivedData atIndex:0]; most certainly will insert "receivedData" into "dataArray" (so long as both exist). "receivedData" can be any sort of NSObject -- need not be a string. If the array is "null" when you log it then the array itself never got created.
(It's important to remember that if an object pointer is nil then method calls on that pointer do not fail but rather silently return zero/nil, so "returns nil" strongly suggests the object never was created.)

Why NSJSONSerialization uses NSData instead of NSString?

Is there any reason for NSJSONSerialization to use NSData instead of NSString for representing JSON data?
NSString seems like a more obvious choice to me...
I imagine it would be more efficient to encourage parsing NSData instead of NSString. If you are parsing a response from a server, for example, you'll get an NSData object representing a buffer of raw bytes returned from the server (note that NSJSONSerialization also includes a method for parsing an NSInputStream directly). Parsing the whole thing into an NSString would be a waste since that would just be an intermediate object that would get thrown out. Instead, NSJSONSerialization is probably parsing the bytes in the NSData object directly and only construct NSStrings for the appropriate keys and values in the resulting data structure.

How to parse base64 image from JSON

What's the reason that I can't parse a base64 string from a JSON request? when I make it a small string it works.
To clarify a little:
else if([connection isEqual:self.appearanceConnection]){
NSArray *arrayOfAppearances = [NSJSONSerialization JSONObjectWithData:[[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding] dataUsingEncoding:NSUTF8StringEncoding]options:NSJSONReadingAllowFragments error:&error];
NSLog(#"het aantal appearances is: %i", arrayOfAppearances.count);
[self syncAppearances:arrayOfAppearances];
}
When I edit it to a small string, I get the response that the length of the received array is 1. If I change it again to the base 64 of the image, the length is 0.
http://cl.ly/image/470Z0X1P3K1b (image form JSON response)
The error I get on the String:
Updated answer:
You now inform us that JSONObjectWithData is reporting an error:
Unterminated string around character 62
Character 62 is the start of the logo. I'm not seeing the end of the JSON in any of your screen snapshots. It looks like it's getting cut off.
You haven't shown us how you are populating data, but it looks almost like you're using a NSURLConnection but trying to parse in didReceiveData as opposed to waiting for the full results and only invoking the the JSON parse in connectionDidFinishLoading. NSURLConnection will break a long response into several calls to didReceiveData and you have to append all of those NSData to a single NSMutableData, and only try to parse it when it's done retrieving everything.
You either need to (a) show us the code where you're loading data and/or (b) share the full JSON. Either your JSON isn't properly terminated or you're trying to parse it before the whole thing is downloaded (probably the latter).
Original answer:
I'm not sure if this is the problem, but your line that says:
NSArray *arrayOfAppearances = [NSJSONSerialization JSONObjectWithData:[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] dataUsingEncoding:NSUTF8StringEncoding]options:NSJSONReadingAllowFragments error:&error];
should simply be:
NSArray *arrayOfAppearances = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
The JSONObjectWithData method takes a NSData, not a NSString.
And, if you're not getting anything returned from this method, you should examine the contents of error and see what it says.
If you're still unable to figure out what the problem is, perhaps you can share the full JSON response with us (give us a URL or upload it somewhere) and we can take a look at it.
With a big thanks to #Rob!
Here a little summary:
Create a variable NSMutableData (don't forget to initialise in the viewdidload)
In the didReceiveData, you append the data to your mutable data using [self.appearancedata appendData:data];
In the connectionDidFinishLoading you parse your JSON

NSData or NSAttributedString with SBJSON

I am using the SBJSON to convert my NSDictionary to a JSON String in my iOS application.
when my dictionary contains a NSAttributedString or an NSData, the SBJSON fails to generate the string representaiton.
Incase of NSAttributedString, the error is :
-JSONRepresentation failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=1 \"JSON serialisation not supported for NSConcreteMutableAttributedString\
Incase of NSData, the error is :
-JSONRepresentation failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=1 \"JSON serialisation not supported for NSConcreteMutableData\"
UserInfo=0x7ed2560 {NSLocalizedDescription=JSON serialisation not
supported for NSConcreteMutableData}"
Solving atleast one of the 2 problems will be a great deal.
Please help.
Thanks
Roshit
JSON doesn't have any datatype to do what you want, but you could convert the NSData into a Base64 encoded string. This can be done automatically with a category on NSData that implements the -proxyForJson method. The problem is when you need to convert it back to NSData on the other end. If the key is known, then you can just Base64 decode that key. But if the data portion can be for any key it's a bit more difficult. You'll have to somehow structure your data so you can determine which strings should be Base64 decoded.
You can not pass NSData object. Solution for problem is, Just use the following line (change response to your nsdata object) and use that string as a value.
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
You can not pass NSAttributedString as a value as well. You have to change NSAttributedString to NSString. Please check OHAttributedLabel lib for more information.

passing JSON from ASIHTTPRequest to django

I've exhausted other threads, so I'm posting this question here. Please pardon any newbie mistakes I've made along the way. I've been reading a lot, and I think I'm getting confused.
The Goal:
I'm trying to pass data from a form in objective-c to my django web service. In an effort to assist with this, I've employed the ASIHTTPRequest class to facilitate information transfer. Once sent to the web service, I'd like to save that data to my sqlite3 database.
Procedure:
On the Objective-C side:
I've stored the inputted form data and their respective keys in an NSDictionary, like this:
NSDictionary *personInfo = [NSDictionary dictionaryWithObjectsAndKeys:firstName.text, #"fName", middleName.text, #"mName", lastName.text, #"lName", nil];
I've added it to my ASIHTTPRequest in a different class by using a delegate. I've made the NSDictionary the same as above in the code block below for simplicity, like so:
NSString *jsonPerson = [personInfo JSONRepresentation];
[request addRequestHeader: #"Content-Type" value:#"application/json; charset=utf-8"];
[request appendPostData:[jsonPerson dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:#"POST"];
[request startAsynchronous];
And a NSLog shows the string I'm passing to look like this, which validates at least in JSONLint
{"mName":"Arthur","lName":"Smith","fName":"Bob"}
Because I'm seeing what appears to be valid JSON coming from my ASIHTTPRequest, and actions are running from requestfinished: rather than requestfailed:, I'm making the assumption that the problem more than likely isn't on the Objective-C side, but rather on the django side.
Here's what I've tried so far:
json.loads(request.POST)
>>expected string or buffer
json.loads('request.POST')
>>no JSON object to decode
json.loads(request.raw_post_data)
>>mNamelNamefName
incoming = request.POST
>>{"mName":"Arthur","lName":"Smith","fName":"Bob"}
incoming = request.POST
onlyValues = incoming.iterlists()
>>(u'{"mName":"Arthur","lName":"Smith","fName":"Bob"}', [u''])
...and a smattering of other seemingly far-fetched variations. I've kept a log, and can elaborate. The only hope I've been able to find is in the last example; it looks like it's treating the entire string as the key, rather than breaking up each dict object and key as I would have expected.
I realize this is terribly elementary and I don't normally ask, but this problem has me particularly stumped. I do also remember reading somewhere that python won't recognize the double-quotes around each object and key, that to get it to something django likes, each should be surrounded by single-quotes. I just don't have any idea how to get them that way.
Thanks!
This might be a little cumbersome but you may try some simple regexp in objective c just to see if that is really the case
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\"" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *json = [regex stringByReplacingMatchesInString:jsonPerson options:0 range:NSMakeRange(0, [jsonPerson length]) withTemplate:#"'"];
There might be some errors because I didn't run the code.