2014-10-29 46 views
1

在我的項目中,有一個被聲明爲靜態的包對象,當客戶單擊「批准訂單」按鈕時,我將包對象序列化爲JSON字符串。目前沒有問題。但是,當我打印序列化的json字符串時,所有與「Int」包中的「ID」轉換爲Bool鍵入json字符串結果。將自定義包對象序列化爲json字符串int到Bool swift

詳情如下過程相關的代碼塊:

這是我「序列化」類:

public class Serializable : NSObject 
{ 

func toDictionary() -> NSDictionary 
{ 
    var aClass : AnyClass? = self.dynamicType 
    var propertiesCount : CUnsignedInt = 0 
    var propertiesInAClass : UnsafeMutablePointer<objc_property_t> = class_copyPropertyList(aClass, &propertiesCount) 
    var propertiesDictionary : NSMutableDictionary = NSMutableDictionary() 

    for(var i = 0; i < Int(propertiesCount); i++) 
    { 
     var property = propertiesInAClass[i] 
     var propName = NSString(CString: property_getName(property), encoding: NSUTF8StringEncoding) 
     var propType = property_getAttributes(property) 
     var propValue : AnyObject! = self.valueForKey(propName!) 

     if(propValue is Serializable) 
     { 
      propertiesDictionary.setValue((propValue as Serializable).toDictionary(), forKey: propName!) 
     } 
     else if(propValue is Array<Serializable>) 
     { 
      var subArray = Array<NSDictionary>() 
      for item in (propValue as Array<Serializable>) 
      { 
       subArray.append(item.toDictionary()) 
      } 
      propertiesDictionary.setValue(subArray, forKey: propName!) 
     } 
     else if(propValue is NSData) 
     { 
      propertiesDictionary.setValue((propValue as NSData).base64EncodedStringWithOptions(nil), forKey: propName!) 
     } 
     else if(propValue is Bool) 
     { 
      propertiesDictionary.setValue((propValue as Bool).boolValue, forKey: propName!) 
     } 
     else if(propValue is NSDate) 
     { 
      var date = propValue as NSDate 
      let dateFormatter = NSDateFormatter() 
      dateFormatter.dateFormat = "Z" 
      var dateString = NSString(format: "/Date(%.0f000%@)/", date.timeIntervalSince1970, dateFormatter.stringFromDate(date)) 
      propertiesDictionary.setValue(dateString, forKey: propName!) 
     } 
     else 
     { 
      propertiesDictionary.setValue(propValue, forKey: propName!) 
     } 
    } 

    return propertiesDictionary 
} 

    func toJson() -> NSData! 
    { 
     var dictionary = self.toDictionary() 
     var err: NSError? 
     return NSJSONSerialization.dataWithJSONObject(dictionary, options:NSJSONWritingOptions(0), error: &err) 
    } 

    func toJsonString() -> NSString! 
    { 
     return NSString(data: self.toJson(), encoding: NSUTF8StringEncoding) 
    } 

    override init() 
    { 

    } 
} 

這是我BagItem類:

class BagItem: Serializable, Hashable { 

var uniqueID: Int = 0 
override var hashValue: Int { return uniqueID.hashValue } 
var bagItemId: String 
var item: Item 
var boughtDate: NSDate! 
var boughtTime: String 
var branch: Branch 
var isMainItem: Bool 

    override init() 
    { 
     self.bagItemId = "" 
     self.item  = Item() 
     self.boughtDate = NSDate() 
     self.boughtTime = "" 
     self.branch  = Branch() 
     self.isMainItem = false 
    } 
} 

func ==(lhs: BagItem, rhs: BagItem) -> Bool 
{ 
    return lhs.uniqueID == rhs.uniqueID 
} 

這是我的「SerializationBag」 class:

class SerializableBag: Serializable 
{ 
    var bag: Array<BagItem> = [] 

    override init() 
    { 

    } 
} 

這是我「ConvertBagToJSON」方法,袋類:如下

static func ConvertBagToJson() -> NSString 
{ 
    var serializer: SerializableBag = SerializableBag() 
    serializer.bag = self.bag 
    return serializer.toJsonString() 
} 

而且我回來JSON字符串結果

{ 
"bag": [ 
    { 
     "branch": { 
      "city": { 
       "cityId": false, 
       "cityName": "" 
      }, 
      "town": { 
       "townName": "", 
       "townId": false 
      }, 
      "branchName": "Branch", 
      "branchId": true, 
      "business": { 
       "businessPhotoPath": "", 
       "businessName": "", 
       "businessId": true 
      }, 
      "branchAddress": "Some Address", 
      "branchTelephone": "" 
     }, 
     "uniqueID": false, 
     "boughtDate": "/Date(1414581909000+0200)/", 
     "item": { 
      "itemName": "Pencil", 
      "itemId": true, 
      "itemPrice": true 
     }, 
     "isMainItem": true, 
     "bagItemId": "9674D47B-0D2F-46CC-BA16-754875AE277D", 
     "hashValue": false, 
     "boughtTime": "00:30" 
    } 
] 
} 

正如你看到的,在JSON字符串,ID爲布爾,但他們必須在Int類型。我怎麼解決這個問題 ?

謝謝你的答案

問候

+0

這是非常有趣的。有沒有其他解決方案來做到這一點? @印記 – user2174358 2014-10-29 13:55:50

+0

對不起,但我刪除了評論。我會寫解決方案。 – rintaro 2014-10-29 13:56:57

回答

3

這是因爲Int橋接到NSNumberNSNumber總是is Bool

在你的情況,你不需要這些行:

else if(propValue is Bool) 
    { 
     propertiesDictionary.setValue((propValue as Bool).boolValue, forKey: propName!) 
    } 

您可以直接刪除它們,因爲NSJSONSerialization可以處理它。

let flg:NSNumber = true 
let id:NSNumber = 1 

let dict:NSDictionary = [ 
    "bool": flg, 
    "id": id 
] 

let jsonDat = NSJSONSerialization.dataWithJSONObject(dict, options: .allZeros, error: nil)! 
let jsonStr = NSString(data: dat, encoding:NSUTF8StringEncoding) 
// -> {"id":1,"bool":true} 

更多相關的例子:

class Foo:NSObject { 
    var flg:Bool = true 
    var id:Int = 1 
} 

let obj = Foo() 
let dict:NSDictionary = [ 
    "flg": obj.valueForKey("flg")!, 
    "id": obj.valueForKey("id")! 
] 

let jsonData = NSJSONSerialization.dataWithJSONObject(dict, options: .allZeros, error: nil)! 
let jsonStr = NSString(data: jsonData, encoding:NSUTF8StringEncoding)! 
// -> {"flg":true,"id":1} 
+0

是的,它工作,非常感謝你@ printaro :) – user2174358 2014-10-29 18:23:14

+0

它正在工作,非常感謝你。 Plz幫助您在同一過程中修復Double和Float值 – 2015-04-06 19:25:26

相關問題