Ios 在swift中将自定义包对象序列化为json字符串int到Bool
在我的项目中,有一个包对象被声明为静态的,当客户单击“批准订单”按钮时,我将包对象序列化为JSON字符串。到目前为止没有问题。但是,当我打印序列化的json字符串时,包中所有带有Int的“id”都会转换为Bool输入json字符串 此过程的相关代码块如下所示:Ios 在swift中将自定义包对象序列化为json字符串int到Bool,ios,iphone,json,serialization,swift,Ios,Iphone,Json,Serialization,Swift,在我的项目中,有一个包对象被声明为静态的,当客户单击“批准订单”按钮时,我将包对象序列化为JSON字符串。到目前为止没有问题。但是,当我打印序列化的json字符串时,包中所有带有Int的“id”都会转换为Bool输入json字符串 此过程的相关代码块如下所示: { "bag": [ { "branch": { "city": { "cityId": false, "cityName":
{
"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"
}
]
}
这是我的“序列化”类:
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()
{
}
}
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
}
class SerializableBag: Serializable
{
var bag: Array<BagItem> = []
override init()
{
}
}
这是我的“序列化包”课程:
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()
{
}
}
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
}
class SerializableBag: Serializable
{
var bag: Array<BagItem> = []
override init()
{
}
}
我返回的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是Bool,但它们必须是Int类型。我怎样才能解决这个问题
谢谢你的回答
这是因为
Int
被桥接到NSNumber
,而NSNumber
总是是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}
这很有趣。没有其他解决方案可以做到这一点吗@对不起,我删除了评论。我会写解决方案。它正在工作,非常感谢。Plz帮助在同一过程中固定双精度和浮点值