ios - swift 4错误的json数组解析

标签 ios json swift decoder

我有这样的 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;
}

我无法解析它。我该如何解决??

最佳答案

解码失败是由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 _ {
}

那么我想当您从服务接收数据时一定有一些奇怪的事情。

关于ios - swift 4错误的json数组解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47865785/

相关文章:

swift - 如何向 CollectionView 添加新数据?

ios - UIImagePicker 自动将照片库中选中的图片保存到 tmp 文件夹中

javascript - 访问从 jQuery 中的 AJAX 对象返回的 JSON

PHP 接收 JSON 但无法解码

ios - 如何修复 : Cannot assign value of type 'CLLocationDegrees' (aka 'Double' ) to type 'Float!' in Swift 3

ios - 两个 iPhone 摄像头的 View 相同吗?

iOS游戏开发困惑

ios - "Safari cannot open the page because the address is invalid"在卸载应用程序的情况下访问 Branch 链接时出现

ios - 自定义 UICollectionViewLayout 不同单元格大小

javascript - 向 json 添加新值