Does NSJSONSerialization deserialize numbers as NSDecimalNumber?

后端 未结 4 2072
甜味超标
甜味超标 2021-02-08 03:37

Take the following piece of code:

NSError *error;
NSString *myJSONString = @\"{ \\\"foo\\\" : 0.1}\";
NSData *jsonData = [myJSONString dataUsingEncoding:NSUTF8St         


        
4条回答
  •  我在风中等你
    2021-02-08 04:19

    To answer the question in the title: No, it doesn't, it creates NSNumber objects. You can easily test this:

    NSArray *a = @[[NSDecimalNumber decimalNumberWithString:@"0.1"]];
    NSData *data = [NSJSONSerialization dataWithJSONObject:a options:0 error:NULL];
    a = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
    NSLog(@"%@", [a[0] class]);
    

    will print __NSCFNumber.

    You can convert that NSNumber object to an NSDecimalNumber with [NSDecimalNumber decimalNumberWithDecimal:[number decimalValue]], but according to the docs for decimalValue

    The value returned isn’t guaranteed to be exact for float and double values.

提交回复
热议问题