Swift 中如何知道 json 的数据类型?

问题描述 投票:0回答:1

解码json文件时,如果它是实数,我需要将其乘以10000,如果它是整数,我需要将其按原样存储。如果有实数的十进制值,则可以区分,但如果有像2.0这样的值,则解码为整数,无法与2区分。

struct Amount: Codable {
  let rawValue: UInt32
  var formattedStr: String {
    formatMoney(rawValue)
  }
      
  init(from decoder: Decoder) throws {
    let container = try decoder.singleValueContainer()
    
    let jsonData = try container.decode(JSON.self)
    let rawValue = jsonData.rawValue
    
    if rawValue is UInt32, let intValue = rawValue as? UInt32 {
      self.rawValue = intValue
    } else if rawValue is Double, let doubleValue = rawValue as? Double {
      self.rawValue = UInt32(doubleValue * 10000)
    } else if rawValue is String, let stringValue = rawValue as? String {
      if stringValue.contains("."), let doubleValue = Double(stringValue) {
        self.rawValue = UInt32(doubleValue * 10000)
      } else if let intValue = UInt32(stringValue) {
        self.rawValue = intValue
      } else {
        throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid format")
      }
    } else {
      throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid format")
    }
  }
}
ios swift decoding swifty-json
1个回答
0
投票

为了区分整数和浮点数,您需要将其转换为 NSNumber 并检查底层 objCType。

尝试以下操作:

  if let number = rawValue as? NSNumber {
      switch Swift.String(cString: number.objCType) {
      case "i", "s", "l", "q", "I", "S", "L", "Q":
          self.rawValue = number.int32Value
      case "f", "d":
          self.rawValue = UInt32(number.doubleValue * 10000)
      case "B", "c", "C":
          // bool value
          ()
      case "*":
          // string value
          ()
      default:
          ()
      }
  }
© www.soinside.com 2019 - 2024. All rights reserved.