如何解析多于一个以空字符结尾的JSON(通过套接字TCP / IP)。
{"ObjectID":"UHJvY1dpcmVsZXNzTXNn","DeviceCode":"RUNEOjI=","ActiveInputNames":"Q2hlY2sgaW4gRmFpbA==","DeviceInputNo":"999999","Activation":false,"Reset":true,"LocationID":"","LocationGroupText":"","ProtocolText":"","CallBackNo":"OTE5MTgyNTcyMjQ5"}��{"ObjectID":"VFBpbmdPYmplY3Q="}��
您可以看到上面的响应,其中有2个JSON以空字符结尾...我可以轻松解析单个JSON,但无法解析多个JSON。
如果有人提出任何解决方案,那就太好了!
答案 0 :(得分:0)
我昨天在Android系统中回答了same question。这是Swift版本
let s = "{\"ObjectID\":\"UHJvY1dpcmVsZXNzTXNn\",\"DeviceCode\":\"RUNEOjI=\",\"ActiveInputNames\":\"Q2hlY2sgaW4gRmFpbA==\",\"DeviceInputNo\":\"999999\",\"Activation\":false,\"Reset\":true,\"LocationID\":\"\",\"LocationGroupText\":\"\",\"ProtocolText\":\"\",\"CallBackNo\":\"OTE5MTgyNTcyMjQ5\"}��{\"ObjectID\":\"VFBpbmdPYmplY3Q=\"}��".components(separatedBy: "��")
for string in s{
// do your parsing here
print(string)
}
您需要做的只是用^分割字符串,您就可以开始了。像以前一样解析JSON。
答案 1 :(得分:0)
首先使用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
使用以下模型解析两个 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"
}
}
解析 JSON
个字符串,例如
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 Root
的解析的strings
对象。
请让我知道是否还有任何困惑。