使用Swifty JSon模型创建模型

时间:2017-07-06 07:32:23

标签: json swift3 swifty-json

[
    {
        "_id": "1212323",
        "row": 1,
        "column": 1,
        "displayType": 0,
        "item": {
            "type": "category_",
            "data": {
                "_id": "595a1446cb91951900b0b4b0",
                "title": "something",
                "fullImage": "http://assets.something.mobi/curated/something (2).jpg",
                "halfImage": "http://assets.something.mobi/curated/something (1).jpg"
            }
        }
    },
    {
        "_id": "595a148ccb91951900b0b4b5",
        "row": 2,
        "column": 1,
        "displayType": 1,
        "item": {
            "type": "curatedlist",
            "data": {
                "_id": "595b34abcb9195190c0ae378",
                "active": "true",
                "title": "sample something list",
                "fullImage": "http://assets.something.mobi/curated/something (2).jpg",
                "halfImage": "http://assets.something.mobi/curated/something (2).jpg"
            }
        }
    }
]

对于SwiftyJSON和Alamofire来说非常新,请帮助我创建一个模型,它可以使用almofire获得JSON响应,但无法为此创建适当的swson json模型

1 个答案:

答案 0 :(得分:1)

我使用两个独立的模型类完成了这个,一个用于直接映射所有值,另一个用于直接从中获取数组。

对于一些刚开始或坚持创建模型和映射值的人可以尝试这些或某人是专家可以建议更好的解决方案来改进实现

1.CategoryModel:NSObject

//declare the media player and file to have class scope
 final File file = new File("x.mp4");
    final String MEDIA_URL = file.toURI().toString();

    // Create a Media
    final Media media = new Media(MEDIA_URL);

    // Create a Media Player
    final MediaPlayer player = new MediaPlayer(media);

2.CategoryListModel:NSObject的

    import UIKit
    import SwiftyJSON

    class CategoryModel: NSObject {
        var resultArray : NSArray!
        var _id : String!
        var row : NSInteger!
        var column : NSInteger!
        var displayType : NSInteger!

        var type : String?

        var _id1 : String?
        var title : String?
        var fullImage : String?
        var halfImage : String?
        // var item


        required init(JsonDashBoard: JSON) {

            _id = JsonDashBoard["_id"].stringValue
            row = JsonDashBoard["row"].intValue
            column = JsonDashBoard["column"].intValue
            displayType = JsonDashBoard["displayType"].intValue

            //MARK:- Inside Item Dictionary
            type = JsonDashBoard["item"]["type"].stringValue
            //MARK:- Inside Item/dataDictionary
            _id1 = JsonDashBoard["item"]["data"]["_id"].stringValue
            title = JsonDashBoard["item"]["data"]["title"].stringValue
            fullImage = JsonDashBoard["item"]["data"]["fullWidthImage"].stringValue
            halfImage = JsonDashBoard["item"]["data"]["halfWidthImage"].stringValue

        }
    }

使用这些模型类,您可以使用以下代码snipet

映射值
  import UIKit

    class CategoryListModel: NSObject {
        var items : NSArray? = nil;
        required init(_items: NSMutableArray) {
            self.items = _items
        }
    }