这是我的JSON
{
"id": 1,
"user": {
"user_name": "Tester",
"real_info": {
"full_name":"Jon Doe"
}
},
"reviews_count": [
{
"count": 4
}
]
}
Run Code Online (Sandbox Code Playgroud)
这是我想要保存的结构(不完整)
struct ServerResponse: Decodable {
var id: String
var username: String
var fullName: String
var reviewCount: Int
enum CodingKeys: String, CodingKey {
case id,
// How do i get nested values?
}
}
Run Code Online (Sandbox Code Playgroud)
我目前正在处理Codable项目中的类型并遇到问题.
struct Person: Codable
{
var id: Any
}
Run Code Online (Sandbox Code Playgroud)
id在上面的代码中可以是a String或an Int.这就是id类型的原因Any.
我知道Any不是Codable.
我需要知道的是我如何才能使它发挥作用.
我正在尝试使用swift 4来解析本地json文件:
{
"success": true,
"lastId": null,
"hasMore": false,
"foundEndpoint": "https://endpoint",
"error": null
}
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的功能:
func loadLocalJSON() {
if let path = Bundle.main.path(forResource: "localJSON", ofType: "json") {
let url = URL(fileURLWithPath: path)
do {
let data = try Data(contentsOf: url)
let colors = try JSONDecoder().decode([String: Any].self, from: data)
print(colors)
}
catch { print("Local JSON not loaded")}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但我一直收到错误:
致命错误:Dictionary不符合Decodable,因为Any不符合Decodable.
我尝试在此stackoverflow页面上使用"AnyDecodable"方法:如何在Swift 4可解码协议中解码具有JSON字典类型的属性,
但它跳转到'catch'语句: catch { print("Local JSON not loaded")使用时.有谁知道如何在Swift 4中解析这个JSON数据?
我用于后端调用的服务返回所有这些 json 结构:
{
"status" : "OK",
"payload" : **something**
}
Run Code Online (Sandbox Code Playgroud)
哪里的东西可以是一个简单的字符串:
{
"status" : "OK",
"payload" : "nothing changed"
}
Run Code Online (Sandbox Code Playgroud)
或嵌套的 json(具有任何属性的任何 json),例如:
{
"status" : "OK",
"payload" : {
"someInt" : 2,
"someString" : "hi",
...
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的结构:
struct GenericResponseModel: Codable {
let status:String?
let payload:String?
}
Run Code Online (Sandbox Code Playgroud)
我想始终将“有效负载”解码为字符串。因此,在第二种情况下,我希望“GenericResponseModel”的有效负载属性包含该字段的 json 字符串,但是如果我尝试解码该响应,则会收到错误消息:
Type 'String' mismatch: Expected to decode String but found a dictionary instead
Run Code Online (Sandbox Code Playgroud)
可以存档我想要的吗?
非常感谢
我正在尝试将字典存储在我的类 Marker 中,但它抛出一个错误,指出它不可编码或不可解码。我可以看到错误是由 [String: Any] 引起的,但我该如何解决呢?
var buttonActions : [String: [String: [String:Any]]] = [:]
Run Code Online (Sandbox Code Playgroud)
保存和加载
func saveData() {
let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("\(fileName).plist")
let encoder = PropertyListEncoder()
do {
let data = try encoder.encode(markerArray)
try data.write(to: dataFilePath!)
print("Saved")
} catch {
print("Error Encoding \(error)")
}
}
func loadData() {
let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("\(fileName).plist")
if let data = try? Data(contentsOf: dataFilePath!){
let decoder = PropertyListDecoder()
do {
markerArray = try decoder.decode([Marker].self, from: data)
} catch { …Run Code Online (Sandbox Code Playgroud)