如何使用带有动态密钥的Swift 4从嵌套JSON中提取数据

时间:2017-11-08 08:19:37

标签: json swift4

我有一个JSON数据结构,使用在上传时创建的唯一键。如果我逐行阅读每个字典项目,我可以阅读所有内容。但是,我试图修改我的代码以使用Swift 4可编码属性。

执行Ray Wenderlich tutorial并阅读Ultimate Guide to JSON Parsing with Swift但遗憾的是并未将我推向天才状态。

JSON看起来像这个简单的例子: 请注意键,如" 123"," 456"," case1"," case2"," u1", " U2"在运行时不知道。

   let json = """
    {
    "things" : {
        "123" : {
        "name" : "Party",
        "owner" : "Bob",
        "isActive" : true,
        "cases" : {
            "case1" : {
                "no" : 1
            },
            "case2" : {
                "no" : 2
            }
        }
        },
        "456" : {
        "name" : "Bus",
        "owner" : "Joe",
        "isActive" : true
        }
    },
    "users" : {
        "u1" : {
        "name" : "Summer"
        },
        "u2" : {
        "name" : "Daffy"
        }
    }
    }
    """

this SO question on flattening JSON之后,我能够为我的大多数数据创建解码器,但不能为嵌套字典创建解码器(在示例中,case就像嵌套字典一样)。我确信我错过了一些简单的事情。

如果我试图包含注释掉的部分,操场将不会运行,不会给出错误。

    struct Thing: Decodable {
    let id: String
    let isActive: Bool
    let name: String
    let owner: String
    //var cases = [Case]()

    init(id: String, isActive: Bool, name: String, owner: String){//}, cases: [Case]?) {
        self.id = id
        self.isActive = isActive
        self.name = name
        self.owner = owner
        //self.cases = cases ?? [Case(id: "none", caseNumber: 0)]
    }
}
struct User: Decodable {
    let id: String
    let name: String
}
struct Case: Decodable {
    let id: String
    let caseNumber: Int
}
struct ResponseData: Decodable {
    var things = [Thing]()
    var users = [User]()


    enum CodingKeys: String, CodingKey {
        case trips
        case users
    }

    private struct PhantomKeys: CodingKey {
        var intValue: Int?
        var stringValue: String
        init?(intValue: Int) { self.intValue = intValue; self.stringValue = "\(intValue)" }
        init?(stringValue: String) { self.stringValue = stringValue }
    }

    private enum ThingKeys: String, CodingKey {
        case isActive, name, owner, cases
    }
    private enum UserKeys: String, CodingKey {
        case name
    }
    private enum CaseKeys: String, CodingKey {
        case id
        case caseNumber = "no"
    }

    init(from decoder: Decoder) throws {

        let outer = try decoder.container(keyedBy: CodingKeys.self)
        let thingcontainer = try outer.nestedContainer(keyedBy: PhantomKeys.self, forKey: .things)

        for key in thingcontainer.allKeys {
            let aux = try thingcontainer.nestedContainer(keyedBy: ThingKeys.self, forKey: key)

            let name = try aux.decode(String.self, forKey: .name)
            let owner = try aux.decode(String.self, forKey: .owner)
            let isActive = try aux.decode(Bool.self, forKey: .isActive)
//            let c = try aux.nestedContainer(keyedBy: CaseKeys.self, forKey: .cases)
//            var cases = [Case]()
//            for ckey in c.allKeys {
//                let caseNumber = try c.decode(Int.self, forKey: .caseNumber)
//                let thiscase = Case(id: ckey.stringValue, caseNumber: caseNumber)
//                cases.append(thiscase)
//            }

            let thing = Thing(id: key.stringValue, isActive: isActive, name: name, owner: owner)//, cases: cases)
            things.append(thing)
        }
        let usercontainer = try outer.nestedContainer(keyedBy: PhantomKeys.self, forKey: .users)

        for key in usercontainer.allKeys {
            let aux = try usercontainer.nestedContainer(keyedBy: UserKeys.self, forKey: key)
            let name = try aux.decode(String.self, forKey: .name)
            let user = User(id: key.stringValue,name: name)
            users.append(user)
        }
    }
}

它适用于事物和用户,但我必须忽略这些情况。请参阅注释中的print输出。

let data = json.data(using: .utf8)!
let things = try JSONDecoder().decode(ResponseData.self, from: data).things
print(things[0])
//Thing(id: "456", isActive: true, name: "Bus", owner: "Joe")

let users = try JSONDecoder().decode(ResponseData.self, from: data).users
print(users[0])
//User(id: "u1", name: "Summer")

我尝试使用this SO question on decoding的指导,这对我来说似乎更清晰,但我没有成功实施。

此代码为also a GIST

我的问题有两个:

  1. 如何在我的Thing中将Case数据作为嵌套数组?
  2. 你能来吗? 建议一个更简洁的方法来编码吗?感觉就像我 重复的事情,但我已经看到了这种包装结构 JSON编码/解码的几个例子。

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

let data = jsonData.data(using: .utf8)
let json = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
let things = json["things"] as! [String:Any]

for (thing_key, thing_value)   in things as [String:Any] {

    let thing = thing_value as! [String:Any]
    if let cases = thing["cases"] as? [String:Any]{
        for (case_key, case_value) in cases {
            print(case_key)
            print(case_value)
        }
    }
}

修改 我最初想念您的问题,这里是您的代码改进以获取案例。这是一个快速的工作,所以可能不是最佳的,但你明白了:

struct Thing: Decodable {
    let id: String
    let isActive: Bool
    let name: String
    let owner: String
    var cases: [Case]?

    init(id: String, isActive: Bool, name: String, owner: String , cases: [Case]?) {
        self.id = id
        self.isActive = isActive
        self.name = name
        self.owner = owner
        self.cases = cases

    }
}
struct User: Decodable {
    let id: String
    let name: String
}
struct Case: Decodable {
    let id: String
    let caseNumber: Int
}
struct ResponseData: Decodable {
    var things = [Thing]()
    var users = [User]()


    enum CodingKeys: String, CodingKey {
        case things
        case users
        case cases
    }

    private struct PhantomKeys: CodingKey {
        var intValue: Int?
        var stringValue: String
        init?(intValue: Int) { self.intValue = intValue; self.stringValue = "\(intValue)" }
        init?(stringValue: String) { self.stringValue = stringValue }
    }

    private enum ThingKeys: String, CodingKey {
        case isActive, name, owner, cases
    }
    private enum UserKeys: String, CodingKey {
        case name
    }
    private enum CaseKeys: String, CodingKey {

        case no
    }

    init(from decoder: Decoder) throws {

        let outer = try decoder.container(keyedBy: CodingKeys.self)
        let thingcontainer = try outer.nestedContainer(keyedBy: PhantomKeys.self, forKey: .things)

        for key in thingcontainer.allKeys {
            let aux = try thingcontainer.nestedContainer(keyedBy: ThingKeys.self, forKey: key)

            let name = try aux.decode(String.self, forKey: .name)
            let owner = try aux.decode(String.self, forKey: .owner)
            let isActive = try aux.decode(Bool.self, forKey: .isActive)


            var cases:[Case]? = []
            do{
                let casescontainer = try aux.nestedContainer(keyedBy: PhantomKeys.self, forKey: .cases)
                    for case_key in casescontainer.allKeys{

                        let caseaux = try casescontainer.nestedContainer(keyedBy: CaseKeys.self, forKey: case_key)
                        let no = try caseaux.decode(Int.self, forKey: .no)
                        let thingCase = Case(id:case_key.stringValue, caseNumber: no)
                        cases?.append(thingCase)
                }

            }catch{ }


            let thing = Thing(id: key.stringValue, isActive: isActive, name: name, owner: owner , cases: cases)
            things.append(thing)
        }
        let usercontainer = try outer.nestedContainer(keyedBy: PhantomKeys.self, forKey: .users)

        for key in usercontainer.allKeys {
            let aux = try usercontainer.nestedContainer(keyedBy: UserKeys.self, forKey: key)
            let name = try aux.decode(String.self, forKey: .name)
            let user = User(id: key.stringValue,name: name)
            users.append(user)
        }
    }
}

这产生了这个输出:

let data = json.data(using: .utf8)!
let things = try JSONDecoder().decode(ResponseData.self, from: data).things
print("-----")
for thing in things{
    print(thing)
}
print("---")
let users = try JSONDecoder().decode(ResponseData.self, from: data).users
for user in users{
    print(user)
}
-----
Thing(id: "456", isActive: true, name: "Bus", owner: "Joe", cases: Optional([]))
Thing(id: "123", isActive: true, name: "Party", owner: "Bob", cases: Optional([__lldb_expr_283.Case(id: "case1", caseNumber: 1), __lldb_expr_283.Case(id: "case2", caseNumber: 2)]))
---
User(id: "u1", name: "Summer")
User(id: "u2", name: "Daffy")

答案 1 :(得分:0)

您可以从当前json中获取密钥,

 jq -r 'keys[]'

在该查询中,通过检索到的每个键在循环中