开发者

objective C get Decimal from Json object

开发者 https://www.devze.com 2023-01-20 19:06 出处:网络
I am trying to parse a json value to a decimal with no success. I am using the following framework http://code.google.com/p/json-framework/

I am trying to parse a json value to a decimal with no success. I am using the following framework

http://code.google.com/p/json-framework/

and my code is as follows

NSDecimal RRP = [[jProduct objectForKey:@"Price"] decimalValue];
NSLog(@"%@", RRP);

I get

Program received signal: “EXC_BAD_ACCESS”.

Just to test I thought I would try this:

NSLog(@"%@", [jProduct obje开发者_运维百科ctForKey:@"Price"]);

42.545

I get the value but obviously I have not set the NSDecimal.

Anybody else had similar experince or can see what I am doing wrong?

Thanks


I'm not familiar with the framework you are using but I would suggest the following:

What is the type returned by [jProduct objectForKey:@"price"]?

You probably need to work around the fact that this is the wrong type - maybe a an NSString?

Try:

NSDecimal RRP = [[NSDecimalNumber decimalNumberWithString:[jProduct objectForKey:@"Price"] decimalValue];

Edit:

Oh and NSDecimal is a struct, not an object so you shouldn't be using NSLog(@"%@"); as the %@ format identifier is for objects.. Instead you can use the basic type format identifiers such as %d or %i and access the components of the structure individually.

However, as you probably want to log a decimal rather than the components of the struct (sign, mantissa etc) then you will probably want to convert it back to an NSDecimalNumber (which is an object).

So it becomes:

NSLog(@"%@", [NSDecimalNumber decimalNumberWithDecimal:RRP]);


[jProduct objectForKey:@"Price"]

may be a NSString. NSString respond to:

 – doubleValue
 – floatValue
 – intValue
 – integerValue
 – longLongValue
 – boolValue

not decimalValue

Verify the class of your data.


store the value in NSNumber

NSNumber *num = [jProduct objectForKey:@"Price"];


An NSDecimal is a struct, not an object. If you want to print an NSDecimal, use NSDecimalString():

NSDecimal rrp = [[jProduct objectForKey:@"Price"] decimalValue];
NSLog(@"%@", NSDecimalString(rrp));


See Decimal & JSON example. I think it will help you.

0

精彩评论

暂无评论...
验证码 换一张
取 消