I have a REST API which expects a file size field to be in bytes. However I am observing that NSJSONSerialization is converting my value to an exponential representation which my server doesn't support.
For example:
unsigned long long fileSize = 100000000000;
NSDictionary *myObject = #{"fileSize": #(fileSize)};
NSData *dataToSend = [NSJSONSerialization dataWithJSONObject:myObject options:0 error:nil];
// send dataToSend to network
On the wire I observe the following is sent:
{ "fileSize" : 1.0e+11 }
Is there any way to force NSJSONSerialization to retain the unsigned long long formatting on the wire?
E.g.
{ "fileSize" : 100000000000 }
Update: Corrected my sample code thanks to Gabriele Petronella
Turns out I was able to solve this just now by explicitly initializing the NSNumber as an unsigned long long.
E.g.
unsigned long long fileSize = 100000000000;
NSDictionary *myObject = #{"fileSize": [NSNumber numberWithUnsignedLongLong:fileSize]};
NSData *dataToSend = [NSJSONSerialization dataWithJSONObject:myObject options:0 error:nil];
// send dataToSend to network
This resulted in the output I expected:
{ "fileSize" : 100000000000 }
I don't see any NSJSONSerialization in your question, anyway converting the dictionary to a NSData instance seems wrong, and it's likely to be causing this encoding issue. Just do something like
NSDictionary *myObject = #{"fileSize": #(fileSize)};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myObject options:0 error:nil];
Related
NSData* jsonData is the http response contains JSON data.
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"jsonString: %#", jsonString);
I got the result:
{ "result": "\u8aaa" }
What is the proper way to encoding the data to the correct string, not unicode string like "\uxxxx"?
If you convert the JSON data
{ "result" : "\u8aaa" }
to a NSDictionary (e.g. using NSJSONSerialization) and print the dictionary
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", jsonDict);
then you will get the output
{
result = "\U8aaa";
}
The reason is that the description method of NSDictionary uses "\Unnnn" escape sequences
for all non-ASCII characters. But that is only for display in the console, the dictionary is correct!
If you print the value of the key
NSLog(#"%#", [jsonDict objectForKey:#"result"]);
then you will get the expected output
說
I don't quite understand what the problem is. AFNetworking has given you a valid JSON packet. If you want the above code to output the character instead of the \u… escape sequence, you should coax the server feeding you the result to change its output. But this shouldn't be necessary. What you most likely want to do next is run it through a JSON deserializer…
NSDictionary * data = [NSJSONSerialization JSONObjectWithData:jsonData …];
…and you should get the following dictionary back: #{#"result":#"說"}. Note that the result key holds a string with a single character, which I'm guessing is what you want.
BTW: In future, I suggest you copy-paste output into your question rather than transcribing it by hand. It'll avoid several needless rounds of corrections and confusion.
How do we convert a NSDictionary into JSON data object? I want to send a JSON data to my server. I am using the below code but facing an issue when it comes to NSDictionary containing Array or further NSDictionary in it. This works well with simple key-value pair.
Issue: It fails on the below line and sets the error object. This works fine if I remove arrays and dictionaries from the source myData dictionary.
NSData *aPostBodyData = [NSJSONSerialization dataWithJSONObject:myData options:0 error:&error];
Where myData looks like:
{
URI = "www.google.com";
addOnTestString = "4,3,";
status = (
"In Progress",
Submitted,
Delivered
);
data =
{
URI = "www.test.com";
testString = "43";
status = (
"In Progress",
Submitted,
Delivered
);
}
}
Error trace:
ok i just write a sample code that includes your situation and it works well.
NSArray * myarray=#[#"a",#"b"];
NSMutableDictionary * dict=[[NSMutableDictionary alloc] initWithObjects:#[#"a",myarray] forKeys:#[#"str",#"arr" ]];
NSData * js=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString * jsString=[[NSString alloc] initWithData:js encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsString);
probable reasons for you get errors may be;
your myData is not in type NSDictionary or NSArray.
or while adding arrays to dictionary you are missing a point.
I've tried converting the same NSDictionary object into NSData and then NSString using NSJSONSerialization and SBJsonWriter several times, and sometimes got a different string. even null. It's quite weird and I can't find any reason. =( JSONKit and YAJL don't have problems like this.
Following is my test code.
for (int i = 0; i < 5; i++) {
NSDictionary *d = [NSDictionary dictionaryWithObject:#"value" forKey:#"key"];
NSData *data = [NSJSONSerialization dataWithJSONObject:d options:0 error:nil];
NSLog(#"%#", [NSString stringWithUTF8String:data.bytes]);
}
and the console output is ...
2012-04-25 01:35:33.113 Test[19347:c07] {"key":"value"}
2012-04-25 01:35:33.114 Test[19347:c07] (null)
2012-04-25 01:35:33.114 Test[19347:c07] {"key":"value"}
2012-04-25 01:35:33.114 Test[19347:c07] {"key":"value"}
2012-04-25 01:35:33.115 Test[19347:c07] (null)
output changes every time I run the test code.
data's byte size is the same, but UTF8-converted string length varies.
The bytes in an NSData object do not necessarily comprise a NUL-terminated string. If you want to convert the data into an NSString, do this instead:
[[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding]
There's a possibility that some parsers write '\0' to the end of the data they return for safety, which explains why they behave more predictably. But you shouldn't rely on that behavior, as you've seen.
Is it possible if I have a NSString and I want to use NSJSONSerialization? How do I do this?
First you will need to convert your NSString to NSData by doing the following
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
then simply use the JSONObjectWithData method to convert it to JSON
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
You need to convert your NSString to NSData, at that point you can use the +[NSJSONSerialization JSONObjectWithData:options:error:] method.
NSString * jsonString = YOUR_STRING;
NSData * data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError * error = nil;
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (!json) {
// handle error
}
You can convert your string to NSData by saying:
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
You can then use it with NSJSONSerialization. Note however that NSJSONSerialization is iOS5 only, so you might be better off using a library like TouchJSON or JSONKit, both of which let you work directly with strings anyway, saving you the step of converting to NSData.
I wrote a blog post that demonstrates how to wrap the native iOS JSON class in a general protocol together with an implementation that use the native iOS JSON class.
This approach makes it a lot easier to use the native functionality and reduces the amount of code you have to write. Furthermore, it makes it a lot easier to switch out the native implementation with, say, JSONKit, if the native one would prove to be insufficient.
http://danielsaidi.com/blog/2012/07/04/json-in-ios
The blog post contains all the code you need. Just copy / paste :)
Hope it helps!
I created a web service which returns JSON or so I think. The data returned look like this:
{"invoice":{"id":44,"number":42,"amount":1139.99,"checkoutStarted":true,"checkoutCompleted":true}}
To me, that looks like valid JSON.
Using native JSON serializer in iOS5, I take the data and capture it as a NSDictionary.
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[request responseData] options:kNilOptions error:&error];
NSLog(#"json count: %i, key: %#, value: %#", [json count], [json allKeys], [json allValues]);
The output of the log is:
json count: 1, key: (
invoice
), value: (
{
amount = "1139.99";
checkoutCompleted = 1;
checkoutStarted = 1;
id = 44;
number = 42;
}
)
So, it looks to me that the JSON data has a NSString key "invoice" and its value is NSArray ({amount = ..., check...})
So, I convert the values to NSArray:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
But, when stepping through, it says that latestInvoice is not a CFArray. if I print out the values inside the array:
for (id data in latestInvoice) {
NSLog(#"data is %#", data);
}
The result is:
data is id
data is checkoutStarted
data is ..
I don't understand why it only return the "id" instead of "id = 44". If I set the JSON data to NSDictionary, I know the key is NSString but what is the value? Is it NSArray or something else?
This is the tutorial that I read:
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
Edit: From the answer, it seems like the "value" of the NSDictionary *json is another NSDictionary. I assume it was NSArray or NSString which is wrong. In other words, [K,V] for NSDictionary *json = [#"invoice", NSDictionary]
The problem is this:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
In actual fact, it should be:
NSDictionary *latestInvoice = [json objectForKey:#"invoice"];
...because what you have is a dictionary, not an array.
Wow, native JSON parser, didn't even notice it was introduced.
NSArray *latestInvoice = [json objectForKey:#"invoice"];
This is actually a NSDictionary, not a NSArray. Arrays wont have keys. You seem capable from here.
Here I think You have to take to nsdictionary like this
NSData* data = [NSData dataWithContentsOfURL: jsonURL];
NSDictionary *office = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSDictionary *invoice = [office objectForKey:#"invoice"];