SWIFT-JSON错误:由于格式不正确,无法读取数据

时间:2019-11-30 10:55:57

标签: ios json swift

如何更正此错误:JSON错误:由于数据格式不正确,因此无法读取?

struct LanguageText: Decodable {
    let id_language: Int
    let language_text: String
}

func textLoad() {
    let switchcase = "loginWords"
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    let postString = "switchcase=\(switchcase)"
    request.httpBody = postString.data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            return // check for fundamental networking error
        }

        do {
            let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
        } catch {
            print("JSON error: \(error.localizedDescription)")
        }

    }.resume()
}

这是JSON格式:

[{"id_language":"15","language_text":"Female"},
 {"id_language":"16","language_text":"Male"},
 {"id_language":"17","language_text":"Other"},
 {"id_language":"1000","language_text":"Hello there!"}]

谢谢!

3 个答案:

答案 0 :(得分:1)

您正在尝试将id_language放入一个Int-Value,但是在您的JSON中,id_language是String。

将id_language更改为String

struct LanguageText: Decodable {
    let id_language: String
    let language_text: String
}

或者您必须编辑JSON文件

[{"id_language":15,"language_text":"Female"},
 {"id_language":16,"language_text":"Male"},
 {"id_language":17,"language_text":"Other"},
 {"id_language":1000,"language_text":"Hello there!"}]

对于解析JSON,我可以推荐this site

答案 1 :(得分:0)

使用它从行数据中获取数组。

  let dataArray = getArrayFromJsonString(rowData: data)

  func getArrayFromJsonString(arrayString:String)-> [[String : Any]] {
    do {
        return try  JSONSerialization.jsonObject(with: 
        arrayString.data(using:
        String.Encoding.utf8, allowLossyConversion: false)!, 
        options:
        JSONSerialization.ReadingOptions.allowFragments) as! [[String :
                Any]]
    } catch let error {
        print("Error: \(error)")
        return []
    }
}

答案 2 :(得分:0)

在模型中,您可以执行以下操作:

struct LanguageText: Decodable {
  let languageId: String
  let languageText: String

  enum CodingKeys: String, CodingKey {
    case languageId = "id_language"
    case languageText = "language_text"
  }
}

在您的do catch中进行data解析:

do {
  let result = try JSONDecoder().decode([LanguageText].self, from: data)
} catch {
  print("JSON error: \(error.localizedDescription)")
}