Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JSON解析在Swift 4中是可解码的_Json_Swift4 - Fatal编程技术网

JSON解析在Swift 4中是可解码的

JSON解析在Swift 4中是可解码的,json,swift4,Json,Swift4,使用下面的json,是否可以在“字段”下获取这些键,并使用for循环逐个打印出来。(路径、公钥、图标、名称、说明) 我的对象模型 struct params: Decodable { let fields: fields? let parName: String? let method: Int? let table: String? let callBackID: String? } struct fields: Decodable {

使用下面的json,是否可以在“字段”下获取这些键,并使用for循环逐个打印出来。(路径、公钥、图标、名称、说明)

我的对象模型

struct params: Decodable {
    let fields: fields?    
    let parName: String?
    let method: Int?
    let table: String?
    let callBackID: String?
}

struct fields: Decodable {
    let name: properties?
    let description: properties?
    let public_key: properties?
    let path: properties?
    let icon: properties?
    let imagelist: properties?
    let templatepath: properties?
    let thumbnail: properties?
}

struct properties: Decodable {
    let source: String?
    let type: String?
}

如果需要循环且键是动态的,请将字段解码为
[String:Properties]

首先,用大写的名称声明结构,并仅将那些属性声明为可选的,可以是
nil

struct Params: Decodable {
    let fields: [String:Properties]
    let parName: String
    let method: Int
    let table: String
    let callBackID: String
}

struct Properties: Decodable {
    let source: String
    let type: String
} 
然后解码JSON,定义一个关键路径数组并枚举该数组(
data
是表示JSON的
data
实例)


试试这个:还有另一个:谢谢@FaysalAhmed,我会查看这些链接。嗨,先生,谢谢你的回复。我想我的问题不清楚。使用此行Fields.name,它将打印“类型”:“值”,“源”:“值”。我想做的是动态打印“字段”下的“键”。在json中,我提供的“fields”有对象“name”、“description”、“public_key”、“path”、“icon”,在某些情况下,它还有另一个对象,比如“id”。对不起,我的英语不好。打印(参数字段)可能会输出“字段”:“名称”、“字段”:“说明”等。
可解码协议基于具体的静态类型。如果键是动态的,请使用传统的
JSONSerialization
。或者将对象解码为
[String:Properties]
并枚举字典。我编辑了答案。非常感谢你,先生。这就是我一直在找的那个D
struct Params: Decodable {
    let fields: [String:Properties]
    let parName: String
    let method: Int
    let table: String
    let callBackID: String
}

struct Properties: Decodable {
    let source: String
    let type: String
} 
do {
    let result = try JSONDecoder().decode(Params.self, from: data)
    let fields = result.fields
    for (key, _) in result.fields {
        print(key)
    }
} catch {
    print("error: ", error)
}