首页 > 解决方案 > 解析错误的 JSON 文件

问题描述

编辑:美化 JSON 文件

以下是我在本地服务器上托管的 JSON 文件

{

"status": "success",

"error": "",

"response": "["{\"ip_id\":\"202\",\"ip_name\":\"P b \",\"small_desc\":\"Growth Hacker\",\"large_desc\":\"Sample description\",\"join_date\":\"\",\"vid_url\":\"https:\/\/www.theug.app\/user_videos\/pr_202.mp4\",\"img_url\":\"https:\/\/www.thnug.app\/user_thumbs\/s.jpg\",\"current_status\":\"0\",\"rate_per_hour\":\"1300\",\"currency\":\"\u20b9\"}","{\"ip_id\":\"217\",\"ip_name\":\"ss dd\",\"small_desc\":\"Talented\",\"large_desc\":\"Sample description2 \",\"join_date\":\"\",\"vid_url\":\"https:\/\/www.thug.app\/user_videos\/d.mp4\",\"img_url\":\"https:\/\/www.tsnug.app\/user_thumbs\/d.jpg\",\"current_status\":\"0\",\"rate_per_hour\":\"3850\",\"currency\":\"\u20b9\"}"]"}

我已经使用以下代码进行了解析。


struct userData: Decodable {
  let ip_id : Int
  let ip_name : String
  let small_desc : String
  let large_desc : String
  let join_date : String
  let vid_url : String
  let img_url : String
  let current_status : Int
  let rate_per_hour : Int
  let currency : String
}

struct WebsiteDescription: Decodable {
    let status: String?
    let error: String?
    let response: [userData]
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let jsonUrlString = "http://0.0.0.0:8000/api-response.json"
        guard let url = URL(string: jsonUrlString) else { return }

        URLSession.shared.dataTask(with: url) { (data, response, err) in
            //perhaps check err
            //also perhaps check response status 200 OK

            guard let data = data else { return }
            print(data)
            do {
                let *users* = try JSONDecoder().decode(userData.self, from: data)
                print(users)

            } catch let jsonErr {
                print("Error serializing json:", jsonErr)
            }

        }.resume()
    }
}

我收到错误消息

Error serializing json: keyNotFound(CodingKeys(stringValue: "ip_id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"ip_id\", intValue: nil) (\"ip_id\").", underlyingError: nil))
  1. 如何获取var users中的数组数据?
  2. 如何在我的课程范围之外使用 var 用户?

标签: arraysobjective-cjsonswiftswift3

解决方案


首先必须解码根对象,WebsiteDescription

let result = try JSONDecoder().decode(WebsiteDescription.self, from: data)

其次,您会遇到另一个问题:key 的值response是嵌套的二级 JSON字符串,而不是 JSON 数组。

不要那样做。JSON 应该看起来像

{"status":"success","error":"","response":[{"ip_id":"202","ip_name":"Prss Pus","small_desc":"Growth Hacker",...

第三,请始终以大写字母开头命名结构。


推荐阅读