简体   繁体   中英

How to get the real value in JSON format string in Objective-C?

let jsonStr =    "[{\"data\":{\"Charge\":0.60,\"sumAmount\":11.86,\"tax\":0.0,\"withdraw\":12.46,\"deduct\":0}}]"

let resultdata = jsonStr.data(using: .utf8)!
do {
    if let jsonArray = try JSONSerialization.jsonObject(with: resultdata, options : .allowFragments) as? [Dictionary<String,Any>]
    {
//       print(jsonArray) // use the json here

        if let tax = jsonArray.first {
            if let newtax = tax["data"] as? Dictionary<String, Any> {
                if let resultTax = newtax["tax"] as? Double {
                    print(resultTax)
//                    print("resultTax")
                }
            }
        }

    } else {
        print("bad json")
    }
} catch let error as NSError {
    print(error)
}

In swift, I can get the tax value. The value is 0.0 .

In objective-c, I have not got the 0.0 value. I have used many API methods. The value is always 0 .

How to get the value 0.0 in Objective-c?

Given that you haven't provided any Objective-C code people can only guess, here is one, it may not be the cause of your issue:

It is the way you are displaying the value, the value is the same .

Assuming in both languages you have correctly parsed the real number and stored the result in a Double / double variable or NSNumber object then:

  • print(doubleVar) in Swift produces 0.0
  • NSLog(@"%g", doubleVar) in Obj-C produces 0
  • NSLog(@"%f", doubleVar) in Obj-C produces 0.000000
  • print(nsNumber) in Swift produces 0
  • NSLog(@"%@", nsNumber) in Obj-C produces 0

These differences are just how a floating-point value is formatted . There is no such floating-point value 0 distinct from 0.0 (or 4.5 distinct from 4.500 etc.)

HTH

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