模型/ Swift中的JSON代码

时间:2017-11-01 20:23:48

标签: json swift model

我需要在Swift中为那个JSON代码创建一个Model,它是一个Dictionaries数组。使用Class或struct更好吗?

{
    "User1": {
    "UserID": 1,
    "Username": "username1",
    "Password": "parola1",
    "Email": "email1@email.com",
    "Phone": "088",
    "Posts":   {"Post1": [{"UrlImage": "image"},{"Title": "tekst"},{"description": "info"}],
        "Post2": [{"UrlImage": "image"},{"Title": "tekst"},{"description": "info"}],
        "Post3": [{"UrlImage": "image"},{"Title": "tekst"},{"description": "info"}]}
    },

    "User2": {
        "UserID": 2,
        "Username": "username2",
        "Password": "parola2",
        "Email": "email2@email.com",
        "Phone": "089",
        "Posts":   {"Post1": [{"UrlImage": "image"},{"Title": "tekst"},{"description": "info"}],
            "Post2": [{"UrlImage": "image"},{"Title": "tekst"},{"description": "info"}],
            "Post3": [{"UrlImage": "image"},{"Title": "tekst"},{"description": "info"}]}
    },
    "User3": {
        "UserID": 3,
        "Username": "username3",
        "Password": "parola3",
        "Email": "email3@email.com",
        "Phone": "090",
        "Posts":   {"Post1": [{"UrlImage": "image"},{"Title": "tekst"},{"description": "info"}],
            "Post2": [{"UrlImage": "image"},{"Title": "tekst"},{"description": "info"}],
            "Post3": [{"UrlImage": "image"},{"Title": "tekst"},{"description": "info"}]}
    }
}

结构模型的外观如何?

1 个答案:

答案 0 :(得分:1)

如果您已经拥有JSON,那么很容易。您可以使用Quicktype从JSON自动生成结构或类。我对你的JSON略微适应,它实际上是一系列的dicts。那么你的模型可能会是这样的:

typealias Users = [User]

struct User: Codable {
    let password: String
    let posts: Posts
    let email: String
    let phone: String
    let userID: Int
    let username: String
}

struct Posts: Codable {
    let post2: [Post]
    let post1: [Post]
    let post3: [Post]
}

struct Post: Codable {
    let urlImage: String?
    let title: String?
    let description: String?
}