-1

我想使用 Unbox 库解析 JSON 文件。JSON 是一个字典数组的数组。我们怎么能做到这一点?我尝试使用 keypath,但无法解析它。我需要部分数组。

我尝试使用单一层次结构并能够解析它。

使用的库:https ://github.com/JohnSundell/Unbox

{
    "content": [
    {
        "section": [
         {
            "title": "Test1"
         },
         {
            "title": "Test2"
         }
         ]
    },
    {
        "section": [
        {
            "title": "Test1"
        },
        {
            "title": "Test2"
        }
        ]
    }
    ]
}

struct Data : Unboxable {
    let title: String

    init(title: String) {
        self.title = title  
    }
    init(unboxer: Unboxer) throws {
        self.title = try unboxer.unbox(key: "title")
    }
}

let dataArray : Data = try unbox(data: Data(contentsOf: url!))
4

1 回答 1

1

您将需要一些嵌套struct的 s 来保存所有可用的数据。最小的数据结构类似于:

struct MyData: Unboxable {
    let content: [Content]
    init(unboxer: Unboxer) throws {
        content = try unboxer.unbox(key: "content")
    }

    // Nested structure for holding `Content` type
    struct Content: Unboxable {
        let section: [Section]
        init(unboxer: Unboxer) throws {
            section = try unboxer.unbox(key: "section")
        }

        // Nested structure for holding `Section` type
        struct Section: Unboxable {
            let title: String
            init(unboxer: Unboxer) throws {
                title = try unboxer.unbox(key: "title")
            }
        }
    }
}

示例 json 和解析策略:

// Eventually, this is the data you maybe got from any server response
let jsonData = """
{
"content": [{
"section": [{
"title": "Test1"
},
{
"title": "Test2"
}
]
},
{
"section": [{
"title": "Test3"
},
{
"title": "Test4"
}
]
}
]
}
""".data(using: .utf8)!

// Now parse this 
do {
    let myData = try unbox(data: jsonData) as MyData
    print(myData.content[0].section[0].title) //Test1
    print(myData.content[0].section[1].title) //Test2
    print(myData.content[1].section[0].title) //Test3
    print(myData.content[1].section[1].title) //Test4
} catch {
    print(error)
}

仅适用于 Swift 4 或更高版本

如果您没有绑定到Swift版本,还有更简单的方法可以实现这一点:

// Your data structure goes this
struct MyData: Codable {
    let content: [Content]

    struct Content: Codable {
        let section: [Section]

        struct Section: Codable {
            let title: String
        }
    }
}
// That's it

// Now you can parse the data like this:
do {
    let myData = try JSONDecoder().decode(MyData.self, from: jsonData)
    print(myData.content[0].section[0].title) //Test1
    print(myData.content[0].section[1].title) //Test2
    print(myData.content[1].section[0].title) //Test3
    print(myData.content[1].section[1].title) //Test4
} catch {
    print(error)
}
于 2018-02-15T16:21:11.590 回答