阅读JSON字典SWIFT

By simon at 2018-02-28 • 0人收藏 • 60人看过

我如何从json字典中快速获取值?这是json

[
    {
        "id": "1",
        "nome": "Federico",
        "cognome": "Loro",
        "data": "1999-07-12"
    },
    {
        "id": "2",
        "nome": "pippo",
        "cognome": "vtuij",
        "data": "0000-00-00"
    },
    {
        "id": "3",
        "nome": "Christian",
        "cognome": "Loro",
        "data": "2018-02-25"
    },
    {
        "id": "4",
        "nome": "pippo",
        "cognome": "vtuij",
        "data": "0000-00-00"
    },
    {
        "id": "5",
        "nome": "pippo",
        "cognome": "vtuij",
        "data": "0000-00-00"
    },
    {
        "id": "6",
        "nome": "pippo",
        "cognome": "vtuij",
        "data": "0000-00-00"
    }
]
我的问题是我不知道如何去做访问字典。

1 个回复 | 最后更新于 2018-02-28
2018-02-28   #1

你所有的JSON值看起来都是字符串,所以你应该创建一个可编码的结构体 喜欢这个:

// name this properly!
struct MyStruct : Codable {
    let id: String
    let nome: String
    let cognome: String
    let data: String
}
现在你可以创建一个JSONDecoder:
let jsonDecoder = JSONDecoder()
let decoded = try! jsonDecoder.decode([MyStruct].self, from: yourJSONString.data(using: .utf8)!)
例如,现在您可以获取第一个项目的id:
decoded.first!.id

登录后方可回帖

Loading...