Search code examples
objective-cjson-deserializationnsjsonserialization

Incorrect result from NSJSON Serialization


I have got a very strange issue when I trying to deserialize my json string, the code is this:

NSString *testString = @"{\"cash\": 99946.222300000000}";
//    NSString *testString = @"{\"cash\": \"99946.222300000000\"}"; //It's correct if I use this one
NSData *jsonData = [testString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"Convertion result is %@",error?@"false":@"true");
NSLog(@"Result data is\n %@",jsonObject);

And the result is :

2017-08-30 18:04:36.430 DAE[45557:2989692] Conversion result is true
2017-08-30 18:04:36.430 DAE[45557:2989692] Result data is
{
    cash = "99946.22229999999";
}

So can anybody tell me if I did anything wrong? and how to solve it?

Really appreciate for any help.


Solution

  • First of all, it’s not wrong, it’s correct.

    So, why you got the incorrect result?

    First, The json value will be converted to a NSNumber object by NSJSONSerialization;

    Then, the -description method of NSDictionary generate the result by stringValue method.

    You should resolve the json value by this way to get the correct string:

    [NSString stringWithFormat:%lf, [jValue doubleValue]]
    

    But you should pay attention to the length of the value, the max length of double is 16, so if you get a number over than it, you will never get the correct result.

    Tell your backend guy that they should convert all the numbers to string before they give them out, because it’s really hard to resolve them correctly if it’s big enough.