在swift中解析JSON并在数组中循环时出错

时间:2018-04-09 07:09:28

标签: json swift

我有一个返回JSON的api,我想解析这个JSON并在我的应用程序中使用它。

我尝试过这样的get方法:swift JSON login REST with post and get response example

代码:

func makeGetCall() {

    // Set up the URL request

    let todoEndpoint: String = "my link"

    guard let url = URL(string: todoEndpoint) else {

        print("Error: cannot create URL")

        return

    }

    let urlRequest = URLRequest(url: url)



    // set up the session

    let config = URLSessionConfiguration.default

    let session = URLSession(configuration: config)



    // make the request

    let task = session.dataTask(with: urlRequest) {

        (data, response, error) in

        // check for any errors

        guard error == nil else {

            print("error calling GET on /public/api/services")

            print(error!)

            return

        }

        // make sure we got data

        guard let responseData = data else {

            print("Error: did not receive data")

            return

        }

        // parse the result as JSON, since that's what the API provides

        do {

            guard let todo = try JSONSerialization.jsonObject(with: responseData, options: [])

                as? [String: Any] else {

                    print("error trying to convert data to JSON")

                    return

            }

            // now we have the todo

            // let's just print it to prove we can access it

            print("The todo is: " + todo.description)



            // the todo object is a dictionary

            // so we just access the title using the "title" key

            // so check for a title and print it if we have one

            guard let todoTitle = todo["name"] as? String else {

                print("Could not get todo title from JSON")

                return

            }

            print("The title is: " + todoTitle)

        } catch  {

            print("error trying to convert data to JSON")

            return

        }

    }

    task.resume()

}

我得到了输出:错误尝试将数据转换为JSON ..

我的JSON是:

[
  {
    "id": 1,
    "name": "Services 1",
    "description": "This is a description of Services 1. This is a description of Services 1 This is a description of Services 1. ",
    "created_at": null,
    "updated_at": null
  },
  {
    "id": 2,
    "name": "Services 2",
    "description": "This is a description of Services 2. This is a description of Services 2 This is a description of Services 2. ",
    "created_at": null,
    "updated_at": null
  }
]

为什么我在解析JSON时遇到错误?

另外,如何循环播放数组并打印每个项目?

例如:

  

服务1描述是:这是服务1的描述。这是   服务1的描述这是服务1的描述。

     

服务2描述是:这是服务2的描述。这是   服务2的描述这是服务2的描述。

2 个答案:

答案 0 :(得分:3)

请仔细阅读JSON。根对象显然是一个数组([]

guard let todos = try JSONSerialization.jsonObject(with: responseData) as? [[String: Any]] else {                    
       print("error trying to convert data to JSON")
       return
  }
  for todo in todos {
      print(todo["name"] as? String ?? "n/a")
  }

但我建议使用Decodable协议。在类

之外声明此结构
struct Service : Decodable {
    let id : Int
    let name, description : String
    let createdAt : String?
    let updatedAt : String?
}

以这种方式解码JSON

do {
   let decoder = JSONDecoder()
   decoder.keyDecodingStrategy = .convertFromSnakeCase
   let todos = try decoder.decode([Service].self, from: responseData)
   for todo in todos {
      print(todo.name)
   }

} catch { print(error) }

旁注:

guard let responseData = data else {行永远不会达到else条款。如果errornil - 已经检查过 - 那么可以保证data有值。

答案 1 :(得分:0)

我认为你犯了一个小错误,你有一个todo列表,解析不会给你todo本身。它会为您提供Array的{​​{1}}

在Swift4中:

todo