简体   繁体   中英

how to parse a decimal value from JSON response

My json response has an amount value like "20.0000"

Am parsing it like

id jsonObject1 = [NSJSONSerialization JSONObjectWithData:responseData7 options:NSJSONReadingAllowFragments error:nil];
AmountArray = [jsonObject1 valueForKey:@"Amt"];

My issue is, when i print(to check) jsonObject1, the amount value is just '20' and not '20.0000'. but the actual value from the webservice is '20.0000'. how to parse it correctly?

The JSON format (compare http://json.org ) distinguishes between strings and numbers . Strings are enclosed in quotation marks, for example

"Hello world"
"20.0000"
"20"

Numbers are not enclosed in quotation marks, for example

20.0000
20

Now "20.0000" and "20" are completely different strings, but 20.0000 and 20 are the same real number .

JSON numbers are converted to NSNumber (or NSDecimalNumber ). But it does not matter how this number is written in the JSON, this is the same number. It does not make sense to say

the actual value from the webservice is '20.0000'

because the value from the web service is the real number 20 , no matter how that number is written.

If you have to distinguish between 20 and 20.0000 for any reason, then the web service must write the values as string (enclosed in quotation marks).

Use NSJSONReadingMutableLeaves instead of NSJSONReadingAllowFragments . The proper documentation can be found at http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html

Let me know if it helped you or not.

Try getting the double value:

id jsonObject1 = [NSJSONSerialization JSONObjectWithData:responseData7 options:NSJSONReadingAllowFragments error:nil];
 AmountArray = [[jsonObject1 valueForKey:@"Amt"] doubleValue];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM