你好每个人都是新开发的app,我有一个json数据,并且有一些键(order_id)有时候order_id值会返回(" order_id":" 188")但是一段时间返回Integer就好了(" order_id":188)。有什么方法可以找到ios(swift)和android中的返回字符串或Integer,感谢
这里是json响应的例子
"orders": [
{
"order_id": "188",
"invoice_id": "OR180413-188",
"order_status": "1"
}
]
还有那样的时间
"orders": [
{
"order_id": 188,
"invoice_id": "OR180413-188",
"order_status": "1"
}
]
答案 0 :(得分:0)
您可以使用:
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)
答案 1 :(得分:0)
Android:
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 :(得分:0)
即使它是 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"
))
}
}
}