如何在swift 3中实现多个值的模型类?

时间:2021-10-06 14:30:31

Here I am having value in JSON in which for some of multiple key value pairs it returning string and for some it is returning array here in custom attributes array in first dictionary in that value key value pair the data present is different and in the second dictionary value key value pair is different here then how to implement the model class for inside array for different key values ?

在这里,我在JSON中有价值,其中对于一些多个键值对,它返回字符串,对于一些它在这里返回数组,在第一个字典中的自定义属性数组中,该值键值对存在的数据是不同的,在第二个字典中值键值对在这里是不同的那么如何为不同键值的内部数组实现模型类?

struct MediaGallery {

    let id : Int
    let mediaType : String
    let label : Any
    let position : Int
    let disabled : Any
    let file : String

    init(dict : [String:Any]) {
        self.id = (dict["id"] as? Int)!
        self.mediaType = (dict["media_type"] as? String)!
        self.label =  dict["label"]!
        self.position = (dict["position"] as? Int)!
        self.disabled = dict["disabled"]!
        self.file = (dict["file"] as? String)!
    }
}
struct AttributeList {

    let label : String
    let value : String
    let code : String

    init(dict : [String:Any]){

        self.label = (dict["label"])! as! String
        self.value = (dict["value"])! as! String
        self.code = (dict["code"])! as! String
    }
}
struct DetailsListAttribute {

    let attributeCode : String
    let value : Any

    init?(dict : [String:Any]) {

        self.attributeCode = dict["attribute_code"] as! String
        print(self.attributeCode)
        if let values = dict["value"] as? String {
            self.value = values
        }
        else {
            if let arr = dict["value"] as? [[String:Any]]{
                var filterArr = [AttributeList]()
                for obj in arr {
                    filterArr.append(AttributeList(dict: obj))
                }
                self.value = filterArr
            } else {
                self.value = [AttributeList]()
            }
        }

    }
}

4 个解决方案

#1


0  

I would suggest please save some time by using this great GIT Library ObjectMapper . it will help you to model your object and convert your model objects (classes and structs) to JSON and vice versa.

我建议请使用这个优秀的GIT库ObjectMapper节省一些时间。它将帮助您建模对象并将模型对象(类和结构)转换为JSON,反之亦然。

#2


0  

I've tried multiple JSON-mapping frameworks that were mentioned in Tj3n comment. They all have pros and cons. Apple suggests you to follow the recommendation given here. Also you should check Codable protocol (swift 4 is required).

我已经尝试了Tj3n评论中提到的多个JSON映射框架。他们都有利有弊。 Apple建议您遵循此处给出的建议。您还应该检查Codable协议(需要swift 4)。

#3


0  

Ok I don't have the whole JSON, and it doesn't seem clear to me.

好吧,我没有完整的JSON,这对我来说似乎并不清楚。

But here is how you can parse and create your model Class easily in Swift with the Codable protocol.

但是这里有一些如何使用Codable协议在Swift中轻松解析和创建模型类。

You can read more about it and/or some examples, tutorials : Ultimate Guide.

您可以阅读更多相关内容和/或一些示例,教程:终极指南。

Briefly, what is the Codable protocol ?

简而言之,什么是Codable协议?

You don't need third party library anymore in order to parse and set the json data to your model class. You juste have to create your class like the JSON is represented. And according to the key-name, it will create the class, properties and everything for you.

您不再需要第三方库,以便将json数据解析并设置为模型类。你应该像JSON一样创建你的类。根据键名,它将为您创建类,属性和一切。

Here is an example with your JSON, I don't know if I understood your JSON formatting, but you got the trick :

这是你的JSON的一个例子,我不知道我是否理解你的JSON格式,但你得到了诀窍:

struct Response: Codable {
    let ca: [CustomAttribute]?

    enum CodingKeys: String, CodingKey {
        case ca = "custom_attributes"
    }
}

struct CustomAttribute: Codable {
    let code: String?
    let value: [Value]?

    struct Value: Codable {
        let label: String?
        let value: String?
        let code: String?

        let avg: String?  // I don't know how your value array is composed
        let count: Int?   // I don't know how your value array is composed
    }

    enum CodingKeys: String, CodingKey {
        case code = "attribute_code"
        case avg = "avg_rating_percent"
    }
}

For me, it looks like something like that.

对我来说,它看起来像那样。

I don't see the whole JSON, but imagine you have the whole JSON as the Response Struct, it contains several objects, like the CustomAttribute Array for example. Then you can define the CustomAttribute structure, and add as many properties as the JSON has.

我没有看到整个JSON,但想象你有整个JSON作为Response Struct,它包含几个对象,例如CustomAttribute Array。然后,您可以定义CustomAttribute结构,并添加与JSON一样多的属性。

Anyway, you can call it this way :

无论如何,你可以这样称呼它:

When you have the response from your API call, you can go :

当您收到API通话的回复时,您可以:

if let data = response.data {
         let decoder = JSONDecoder()
         let response = try! decoder.decode(Response.self, from: data)
         print("Only printing the Custom Attribute : \(response.ca!)")
} 

I decode the whole json data as an Object Response (like my Struct). And I pass to my response callback, or

我将整个json数据解码为Object Response(就像我的Struct)。我转到我的回复回复,或者

#4


0  

this might be late but I think this will helps others

这可能会迟到但我认为这会对其他人有所帮助

The model class which are varies for frameworks like SwiftyJSON, simple swift class, Gloss or swift codable (Swift 4). you can easily generate model class online with your customization jsoncafe.com

模型类因SwiftyJSON,简单的swift类,Gloss或swift codable(Swift 4)等框架而异。您可以使用自定义jsoncafe.com轻松在线生成模型类

#1


0  

I would suggest please save some time by using this great GIT Library ObjectMapper . it will help you to model your object and convert your model objects (classes and structs) to JSON and vice versa.

我建议请使用这个优秀的GIT库ObjectMapper节省一些时间。它将帮助您建模对象并将模型对象(类和结构)转换为JSON,反之亦然。

#2


0  

I've tried multiple JSON-mapping frameworks that were mentioned in Tj3n comment. They all have pros and cons. Apple suggests you to follow the recommendation given here. Also you should check Codable protocol (swift 4 is required).

我已经尝试了Tj3n评论中提到的多个JSON映射框架。他们都有利有弊。 Apple建议您遵循此处给出的建议。您还应该检查Codable协议(需要swift 4)。

#3


0  

Ok I don't have the whole JSON, and it doesn't seem clear to me.

好吧,我没有完整的JSON,这对我来说似乎并不清楚。

But here is how you can parse and create your model Class easily in Swift with the Codable protocol.

但是这里有一些如何使用Codable协议在Swift中轻松解析和创建模型类。

You can read more about it and/or some examples, tutorials : Ultimate Guide.

您可以阅读更多相关内容和/或一些示例,教程:终极指南。

Briefly, what is the Codable protocol ?

简而言之,什么是Codable协议?

You don't need third party library anymore in order to parse and set the json data to your model class. You juste have to create your class like the JSON is represented. And according to the key-name, it will create the class, properties and everything for you.

您不再需要第三方库,以便将json数据解析并设置为模型类。你应该像JSON一样创建你的类。根据键名,它将为您创建类,属性和一切。

Here is an example with your JSON, I don't know if I understood your JSON formatting, but you got the trick :

这是你的JSON的一个例子,我不知道我是否理解你的JSON格式,但你得到了诀窍:

struct Response: Codable {
    let ca: [CustomAttribute]?

    enum CodingKeys: String, CodingKey {
        case ca = "custom_attributes"
    }
}

struct CustomAttribute: Codable {
    let code: String?
    let value: [Value]?

    struct Value: Codable {
        let label: String?
        let value: String?
        let code: String?

        let avg: String?  // I don't know how your value array is composed
        let count: Int?   // I don't know how your value array is composed
    }

    enum CodingKeys: String, CodingKey {
        case code = "attribute_code"
        case avg = "avg_rating_percent"
    }
}

For me, it looks like something like that.

对我来说,它看起来像那样。

I don't see the whole JSON, but imagine you have the whole JSON as the Response Struct, it contains several objects, like the CustomAttribute Array for example. Then you can define the CustomAttribute structure, and add as many properties as the JSON has.

我没有看到整个JSON,但想象你有整个JSON作为Response Struct,它包含几个对象,例如CustomAttribute Array。然后,您可以定义CustomAttribute结构,并添加与JSON一样多的属性。

Anyway, you can call it this way :

无论如何,你可以这样称呼它:

When you have the response from your API call, you can go :

当您收到API通话的回复时,您可以:

if let data = response.data {
         let decoder = JSONDecoder()
         let response = try! decoder.decode(Response.self, from: data)
         print("Only printing the Custom Attribute : \(response.ca!)")
} 

I decode the whole json data as an Object Response (like my Struct). And I pass to my response callback, or

我将整个json数据解码为Object Response(就像我的Struct)。我转到我的回复回复,或者

#4


0  

this might be late but I think this will helps others

这可能会迟到但我认为这会对其他人有所帮助

The model class which are varies for frameworks like SwiftyJSON, simple swift class, Gloss or swift codable (Swift 4). you can easily generate model class online with your customization jsoncafe.com

模型类因SwiftyJSON,简单的swift类,Gloss或swift codable(Swift 4)等框架而异。您可以使用自定义jsoncafe.com轻松在线生成模型类