ios - SWIFT - JSON 错误 : The data couldn’t be read because it isn’t in the correct format

标签 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!"}]

谢谢!

最佳答案

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

将 id_language 更改为字符串

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

关于ios - SWIFT - JSON 错误 : The data couldn’t be read because it isn’t in the correct format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59115450/

相关文章:

ios - 获取 quickblox 聊天中的用户列表

javascript - 如何在控制台页面查看URI的内容?

python - 从字符串中提取哈希数字

ios - Swift 中开关盒的穷举条件

ios - Swift 2.0、SpriteKit - 不使用页面的 ScrollView 。

ios - 在iOS中使用TableViews创建多列表

ios - 无法使用通用链接

r - 将 SPSS 数据中的标签和值导出为 Json

swift - 未填充 append 重叠的 UIBezierPath

ios - 在 SwiftUI 扩展中动态数据传递和呈现网格图像的 View