Mano
Mano

Reputation: 740

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?

Upvotes: 1

Views: 2177

Answers (3)

Martin R
Martin R

Reputation: 539685

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).

Upvotes: 3

Meet
Meet

Reputation: 4934

Try getting the double value:

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

Upvotes: 0

Dunes Buggy
Dunes Buggy

Reputation: 1819

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.

Upvotes: 0

Related Questions