首先,使用components(separatedBy:) 将两个 JSON 分开,这样我们就可以单独解析它们。
let str = """
{"ObjectID":"UHJvY1dpcmVsZXNzTXNn","DeviceCode":"RUNEOjI=","ActiveInputNames":"Q2hlY2sgaW4gRmFpbA==","DeviceInputNo":"999999","Activation":false,"Reset":true,"LocationID":"","LocationGroupText":"","ProtocolText":"","CallBackNo":"OTE5MTgyNTcyMjQ5"}��{"ObjectID":"VFBpbmdPYmplY3Q="}��
"""
let jsonArr = str.components(separatedBy: "��")
jsonArr 包含 JSON Strings。让我们看看如何解析它们。
我们将使用 Codable 通过以下 model 解析两个 JSON。
struct Root: Codable {
let objectID: String
let deviceCode: String?
let activeInputNames: String?
let deviceInputNo: String?
let activation: Bool?
let reset: Bool?
let locationID: String?
let locationGroupText: String?
let protocolText: String?
let callBackNo: String?
enum CodingKeys: String, CodingKey {
case objectID = "ObjectID"
case deviceCode = "DeviceCode"
case activeInputNames = "ActiveInputNames"
case deviceInputNo = "DeviceInputNo"
case activation = "Activation"
case reset = "Reset"
case locationID = "LocationID"
case locationGroupText = "LocationGroupText"
case protocolText = "ProtocolText"
case callBackNo = "CallBackNo"
}
}
解析JSONstrings之类的,
let parsedObjs = jsonArr.map { (str) -> Root? in
if let data = str.data(using: .utf8) {
do {
let obj = try JSONDecoder().decode(Root.self, from: data)
return obj
} catch {
print(error)
return nil
}
}
return nil
}
parsedObjs 将包含 为 JSON strings 解析的 Root 对象。
如果对此有任何困惑,请告诉我。