解析一个坏的JSON文件

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

编辑:美化的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. 如何获取数组数据 变种用户?
  2. 我如何在我的类的范围外使用var users?
arrays objective-c json swift swift3
1个回答
2
投票

首先必须对根对象进行解码。WebsiteDescription

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

其次,你会遇到另一个问题。键的值 response 是一个嵌套的二级JSON 绳子 而不是JSON数组。

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

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

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

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