提问者:小点点

在Swift中读取json[关闭]


我需要帮助在ios Swift中阅读json。我知道我可以使用decodable,但这是我的JSON的一个示例。当我尝试xith decodable时,我总是得到一个零变量。

谢谢你的帮助

[
     {
       "name": "Bob",
       "age": "16",
       "employed": "No"
     },
     {
       "name": "Vinny",
       "age": "56",
       "employed": "Yes"
     }
]

这是我的密码,用可解码的

struct personResult: Decodable{
    var person: [Person]
}

struct Person:Decodable{
    var name: String
    var age: String
    var employed: String
}

这就是我的职责

    
    func getJson() {
      let url = URL(string: myUrl)!

      let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
        if let error = error {
          print("Error : \(error)")
          return
        }
        
        guard let httpResponse = response as? HTTPURLResponse,
              (200...299).contains(httpResponse.statusCode) else {
          print("Error with the response, unexpected status code: \(response)")
          return
        }
        
        if let data = data {
            
            print(data)
            do {
                let result = try JSONDecoder().decode(personResult.self, from: data)
                print(result)

                
            }catch _ {
                print("errror during json decoder")
            }
            
        }
      })
      task.resume()
    }
    
    
    
}

我总是在我的catch中输入,并打印错误消息


共1个答案

匿名用户

您的JSON是一个数组而不是字典,只是您的Person结构

struct Person:Decodable{
var name: String
var age: String
var employed: String
}

则在函数中:

func getJson() {
  let url = URL(string: myUrl)!

  let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
    if let error = error {
      print("Error : \(error)")
      return
    }
    
    guard let httpResponse = response as? HTTPURLResponse,
          (200...299).contains(httpResponse.statusCode) else {
      print("Error with the response, unexpected status code: \(response)")
      return
    }
    
    if let data = data {
        
        print(data)
        do {
            let result = try JSONDecoder().decode([Person].self, from: data)
            print(result)

            
        }catch let error {
            print(error)
        }
        
    }
  })
  task.resume()
}
}