在Swift3中解析JSON时,为什么格式很奇怪?

时间:2016-12-19 13:26:09

标签: ios json swift api

我在使用Oxford Dictionary API解析JSON数据方面遇到了困难。我可以检索JSON数据,此时,没有问题。但格式有点奇怪。在OXford Document的JSON数据示例中,它看起来像;

"results": [
{
  "id": "string",
  "language": "string",
  "lexicalEntries": [
    {
      "entries": [
        {..........

与上面的示例不同,我的JSON中的数组不是由[]引用的,而是() 为什么会这样?

更新

我用Alamofire来制作它。代码是;

   func getJSONData() {

    let appId = ""
    let appKey = ""
    let language = "en"
    let word = "play"
    let word_id = word.lowercased()
    let url = URL(string: "https://od-api.oxforddictionaries.com/api/v1/entries/\(language)/\(word_id)")!
    var request = URLRequest(url: url)
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.addValue(appId, forHTTPHeaderField: "app_id")
    request.addValue(appKey, forHTTPHeaderField: "app_key")

    Alamofire.request(request).responseJSON { response in
        print("Request \(response.request)")  // original URL request
        print("Response \(response.response)") // HTTP URL response
        print("Data \(response.data)")     // server data
        print("Result \(response.result)")   // result of response serialization

        if let JSON = response.result.value {
            print("JSON: \(JSON)")
        }
    }
}

我遵循牛津字典文档中的所有代码,但打印出的JSON远非文档中的JSON。所以我试图使用Alamofire,希望它正常工作,但结果是一样的。 https://developer.oxforddictionaries.com/documentation

UPDATE2

好的,我理解为什么这是一个错误。对于可能遇到同样问题的人,我发布了我遇到的问题的答案。

   enum JSONError: String, Error {
    case NoData = "ERROR: no data"
    case ConversionFailed = "ERROR: conversion from JSON failed"
}

func jsonParser() {

    let appId = ""
    let appKey = ""
    let language = "en"
    let word = "Ace"
    let word_id = word.lowercased() //word id is case sensitive and lowercase is required
    let url = URL(string: "https://od-api.oxforddictionaries.com:443/api/v1/entries/\(language)/\(word_id)")!

    var request = URLRequest(url: url)
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.addValue(appId, forHTTPHeaderField: "app_id")
    request.addValue(appKey, forHTTPHeaderField: "app_key")

    URLSession.shared.dataTask(with: request) { (data, response, error) in
        do {
            guard let data = data else {
                throw JSONError.NoData
            }
            guard let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary else {
                throw JSONError.ConversionFailed
            }

            if let stringJSON = String(data: data, encoding: String.Encoding.utf8) {
                print(stringJSON)
            }

            print(json)

        } catch let error as JSONError {
            print(error.rawValue)
        } catch let error as NSError {
            print(error.debugDescription)
        }
        }.resume()
}

Strange printed JSON format这篇文章对我有所帮助。这让我有点困扰。非常感谢@EricAya

0 个答案:

没有答案