json序列化一个对象

时间:2017-03-11 15:08:26

标签: json swift serialization

我是swift的新手,并尝试使用带有一些属性的api来发出http post请求。 我已经定义了以下类

班级订单{

var address1 : String?
var address2 : String?
var cellPhone : String?
var city : String?
var countryName : String?
var orderDate : String?
var orderStatus : Int?
var orderedProductList : Array<OrderedProduct>?
var paymentTransactionId : String?
var state : String?
var zip : String?
var countryId : Int?
var orderId : Int?
var orderTotal : Int?
var paymentMethodId : Int?
var userId : Int?

init(address1:String?, address2:String?, cellPhone:String?, city:String?, countryName:String?, orderDate:String?,orderStatus:Int?,orderedProductList:Array<OrderedProduct>?, paymentTransactionId:String?, state:String?, zip:String?, countryId:Int?, orderId:Int?, orderTotal:Int?, paymentMethodId:Int?, userId:Int?)
{


    self.address1 = address1
    self.address2 = address2
    self.cellPhone = cellPhone
    self.city = city
    self.countryName = countryName
    self.countryId = countryId
    self.orderDate = orderDate
    self.orderStatus = orderStatus
    self.paymentTransactionId = paymentTransactionId
    self.state = state
    self.zip = zip
    self.orderId = orderId
    self.orderTotal = orderTotal
    self.paymentMethodId = paymentMethodId
    self.userId = userId
    self.orderedProductList = orderedProductList
}

}

订单实例是:

var totalOrderInfo = Order(address1: address, address2: apartment, cellPhone: phone, city: city, countryName: cName, orderDate: "\(year)-\(month)-\(day)T\(hour):\(minutes):\(seconds)", orderStatus: 1, orderedProductList: orderedProductList, paymentTransactionId: transctionID, state: state, zip: zip, countryId: cId, orderId: 0, orderTotal: returnValue1, paymentMethodId: 1, userId: userID)

totalOrderInfo的JSON表示如下:

{"address1":"Mirpur","address2":"D6, f8","cellPhone":"01852540565","city":"fghff","countryName":"Bangladesh","orderDate":"2017-02-25T11:28:24","orderStatus":1,"orderedProductList":[{"discount":0.0,"orderDetailId":0,"price":30000.0,"quantity":1,"shippingCharge":50.0,"supplierId":0,"tax":0.0,"type":{"isBook":false,"typeId":0},"productId":5,"productViews":0},{"discount":0.0,"orderDetailId":0,"price":50000.0,"quantity":1,"shippingCharge":50.0,"supplierId":0,"tax":0.0,"type":{"isBook":false,"typeId":0},"productId":8,"productViews":0},{"discount":0.0,"orderDetailId":0,"price":2000.0,"quantity":1,"shippingCharge":50.0,"supplierId":0,"tax":0.0,"type":{"isBook":false,"typeId":0},"productId":9,"productViews":0}],"paymentTransactionId":"1215455638874521","state":"fyy","zip":"4525","countryId":23,"orderId":0,"orderTotal":82000.0,"paymentMethodId":1,"userId":0}

如何序列化totalOrderInfo实例并获取上述JSON ??

谢谢

2 个答案:

答案 0 :(得分:0)

您可以使用库,例如​​:Object Mapper

在您的情况下,您的班级Order将是这样的:

class Order: Mappable {
    var address1 : String?
    var address2 : String?
    var cellPhone : String?
    var city : String?
    var countryName : String?
    var orderDate : String?
    var orderStatus : Int?
    var orderedProductList : Array<OrderedProduct>?
    var paymentTransactionId : String?
    var state : String?
    var zip : String?
    var countryId : Int?
    var orderId : Int?
    var orderTotal : Int?
    var paymentMethodId : Int?
    var userId : Int?

    init?(map: Map){
    }

    init(address1:String?, address2:String?, cellPhone:String?, city:String?, countryName:String?, orderDate:String?,orderStatus:Int?,orderedProductList:Array<OrderedProduct>?, paymentTransactionId:String?, state:String?, zip:String?, countryId:Int?, orderId:Int?, orderTotal:Int?, paymentMethodId:Int?, userId:Int?)
    {
        self.address1 = address1
        self.address2 = address2
        self.cellPhone = cellPhone
        self.city = city
        self.countryName = countryName
        self.countryId = countryId
        self.orderDate = orderDate
        self.orderStatus = orderStatus
        self.paymentTransactionId = paymentTransactionId
        self.state = state
        self.zip = zip
        self.orderId = orderId
        self.orderTotal = orderTotal
        self.paymentMethodId = paymentMethodId
        self.userId = userId
        self.orderedProductList = orderedProductList

    }

    mutating func mapping(map: Map){
        address1 <- map["address1"]
        address2 <- map["address2"]
        cellPhone <- map["cellPhone"]
        city <- map["city"]
        countryName <- map["countryName"]
        countryId <- map["countryId"]
        orderDate <- map["orderDate"]
        orderStatus <- map["orderStatus"]
        paymentTransactionId <- map["paymentTransactionId"]
        state <- map["state"]
        zip <- map["zip"]
        orderId <- map["orderId"]
        orderTotal <- map["orderTotal"]
        paymentMethodId <- map["paymentMethodId"]
        userId <- map["userId"]
        orderedProductList <- map["orderedProductList"]
    }

}

由于您的代码中还有Array<OrderedProduct>,因此您必须对OrderedProduct类执行相同操作。

之后,您可以使用以下命令将模型对象转换为JSON字符串:

let order = Order(address1, address2.......)
let jsonString = order.toJSONString(prettyPrint: true)

如果您想了解有关该库以及如何安装它的更多信息,可以在Github Project页面上查看官方文档

答案 1 :(得分:0)

通过序列化JSON数据,您将获得字典,因此在Order类中添加新的初始化方法,如下所示:

class Order {
.
.
.
.

init(dictionary: [String: AnyObject]) {
        super.init()
address1 = dictionary["address1"] as? String
address2 = dictionary["address2"] as? String
// and so on
}

然后在加载JSON数据的地方,从JSON字典中初始化对象:

do {
    let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary

    let order = Order(dictionary: json)

 } catch let error as NSError {
            print(error)
 }

(其中data是从API收到的数据)