【问题标题】:Serializing custom bag object to json string int to Bool in swift在swift中将自定义包对象序列化为json字符串int到Bool
【发布时间】:2014-10-29 12:32:13
【问题描述】:

在我的项目中,有一个声明为静态的包对象,当客户单击“批准订单”按钮时,我将包对象序列化为 JSON 字符串。到目前为止没有问题。但是,当我打印序列化的 json 字符串时,包中所有带有 Int 的“ID”都转换为 Bool 类型的 json 字符串结果。

该流程的相关代码块如下:

这是我的“序列化”类:

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 SerializableBag: Serializable
{
    var bag: Array<BagItem> = []

    override init()
    {

    }
}

这是我在 Bag 类中的 "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 是 Bool,但它们必须是 Int 类型。我怎么解决这个问题 ?

感谢您的回答

最好的问候

【问题讨论】:

  • 这很有趣。没有其他解决方案可以做到这一点吗? @rintaro
  • 对不起,我删除了评论。我会写解决方案。

标签: ios iphone json serialization swift


【解决方案1】:

这是因为Int 桥接到NSNumber 并且NSNumber 始终是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}

【讨论】:

  • 它工作正常,非常感谢。请帮助在同一过程中修复 Double 和 Float 值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-11
  • 1970-01-01
  • 1970-01-01
  • 2013-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多