【问题标题】:how to check a key value is string or Integer (ios,Android) both如何检查键值是字符串还是整数(ios,Android)
【发布时间】:2018-04-13 12:52:44
【问题描述】:

大家好,我是应用程序开发的新人,我有一个 json 数据并且有键 (order_id) 有时 order_id 值是返回 ("order_id": "188") 但有时会返回这样的整数 ("order_id" : 188) . 有什么方法可以在 ios(swift) 和 android 中找到返回字符串或整数,谢谢

这里是json响应的例子

"orders": [
        {
            "order_id": "188",
            "invoice_id": "OR180413-188",
            "order_status": "1"
        }
        ]

还有一段时间

"orders": [
            {
                "order_id": 188,
                "invoice_id": "OR180413-188",
                "order_status": "1"
            }
            ]

【问题讨论】:

  • 根据您的回复,它似乎只是字符串格式。您可以将此字符串转换为 Int。
  • @AbhirajsinhThakore 有时它会是这样的整数(“order_id”:188)
  • 听起来您应该在返回 JSON 数据的方式上更加一致。您的数据中不应有不同的格式。无论在何处创建此 JSON 数据,请确保仅将 order_id 创建为字符串值。
  • 解析为 Any 并将其转换为字符串
  • iOS 和 Android 是两个完全不同的平台,除非您在 Android 设备上使用 Swift 编程,否则没有共同的答案。我强烈建议提出这 2 个单独的问题,否则可能会被认为“过于宽泛”。

标签: android ios swift


【解决方案1】:

安卓:

Object order_id = jsonarray.getJsonObject(0).getInt("order_id");
Object invoice_id = jsonarray.getJsonObject(0).getString("invoice_id");
Object order_status= jsonarray.getJsonObject(0).getInt("order_status");

if(order_id instanceOf String)
    // do what you want
.....

也许这会对你有所帮助

【讨论】:

    【解决方案2】:

    斯威夫特

    你可以像这样使用:

     let str = "188" // Your response string or Int here
        var sInt:Int = Int()
    
        // Check if 's' is a String
    
        if str is String {
            print("Yes, it's a String")
            sInt = Int(str)!
            print(sInt)
        }else{
            print("Not a string")
        }
    

    另一种方式是:

    您可以强制将其转换为字符串,然后将其转换为 Int 以获得更安全的一面

    let str = "\(strResponse)" // Your String here
    let strToInt = Int(str)
    

    【讨论】:

    • 我认为将其强制转换为字符串然后返回 Int 对您有用。
    【解决方案3】:

    你可以将它解码为字符串,即使它是使用 Swift 4 的整数:

    struct Order: Decodable {
    
        private enum CodingKeys: String, CodingKey {
            case orderId = "order_id"
        }
    
        let orderId: String
    
        init(from decoder: Decoder) throws {
            let container = try? decoder.container(keyedBy: CodingKeys.self)
    
            if let orderId = try container?.decodeIfPresent(String.self, forKey: .orderId) {
                self.orderId = orderId
            } else if let orderId = try container?.decodeIfPresent(Int.self, forKey: .orderId)  {
                self.orderId = String(orderId)
            } else {
                throw DecodingError.dataCorrupted(DecodingError.Context(
                    codingPath: decoder.codingPath,
                    debugDescription: "Couldn't decode orderId"
                ))
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 2018-03-20
      • 2014-12-20
      • 1970-01-01
      • 2011-09-01
      • 2021-10-21
      相关资源
      最近更新 更多