本文介绍了如果JSON数据包含换行符(&Q;),则SWIFT 4无法正确解码
(&Q;)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果json数据包含新行(""),则SWIFT 4无法正确解码 ")。我能为这个案例做些什么。请查看我的样例代码:var userData = """
[
{
"userId": 1,
"id": 1,
"title": "Title
with newline",
"completed": false
}
]
""".data(using: .utf8)
struct User: Codable{
var userId: Int
var id: Int
var title: String
var completed: Bool
}
do {
//here dataResponse received from a network request
let decoder = JSONDecoder()
let model = try decoder.decode([User].self, from:userData!) //Decode JSON Response Data
print(model)
} catch let parsingError {
print("Error", parsingError)
}
如果我按如下所示更改用户数据值,则它可以正确解码。
var userData = """
[
{
"userId": 1,
"id": 1,
"title": "Title \n with newline",
"completed": false
}
]
""".data(using: .utf8)
推荐答案
这是无效的json。 "" [ { "userid":1, "id":1, "title":"标题 带换行符", "Complete":False } ] "
请使用以下代码
var userData : [[String:Any]] =
[
[
"userId": 1,
"id": 1,
"title": "Title
with newline",
"completed": false
]
]
struct User: Codable{
var userId: Int
var id: Int
var title: String
var completed: Bool
}
do {
//here dataResponse received from a network request
let data = try? JSONSerialization.data(withJSONObject: userData, options:
[])
let decoder = JSONDecoder()
let model = try decoder.decode([User].self, from:data!) //Decode JSON
Response Data
print(model)
} catch let parsingError {
print("Error", parsingError)
}
这篇关于如果JSON数据包含换行符(&Q;),则SWIFT 4无法正确解码 (&Q;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!