swift 4错误的json数组解析

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

我有这样的json:

{"result":0,"data":[{\"ID":7,"TITLE":"123"},{\"ID":8,"TITLE":"123"}]}

我有这样的结构:

struct ResponseResult: Decodable {
let result: Int
let data: [IdResponseResult]
}

struct IdResponseResult: Decodable {
let ID: Int
let TITLE: String
}

所以,当我运行这样的请求时:

Alamofire.request("https://xxx.xxx.xxx",headers:headers).responseJSON { response in
            if let json = response.data {
                let decoder = JSONDecoder()
                let result = try? decoder.decode(ResponseResult.self, from: json)
                print(response.value)
                completion(result)
            }
        }

并打印response.value我得到这个:

   data =     (
               {
            "ID" = 7;
            TITLE = 123;
        },
                {
            "ID" = 8;
            TITLE = 123;
        }
    );
    result = 0;
}

我无法解析它。我怎么解决?

ios json swift decoder
1个回答
1
投票

解码失败是由struct resp2引起的

struct resp2: Decodable {
  let ID: Int
  let TITLE: String
 }

你定义TITLE:String,但在JSON你有一个Int "TITLE":123。如果你真的想要一个String(有意义,因为它是一个“标题”),你可能需要修复服务器端。


编辑:

我现在尝试了Decodable,我可以恢复您的结构,您可以查看:

let string = "{\"result\": 0,\"data\": [{\"ID\": 7,\"TITLE\": \"123\"}, {\"ID\": 8,\"TITLE\": \"123\"}]}"
let data = string.data(using: .utf8)
do {
    let decoder = JSONDecoder()
    let result = try? decoder.decode(ResponseResult.self, from: data!)
    print(result?.data.first?.TITLE ?? "") // 123
} catch _ {
}

然后我想当你从服务收到数据时,必须有一些奇怪的东西。

© www.soinside.com 2019 - 2024. All rights reserved.