parse - swift json教學




在swift中創建JSON (4)

•Swift 4。1,2018年4月

這是一種更通用的方法 ,可以通過使用字典中的值來創建JSON字符串:

struct JSONStringEncoder {
    /**
     Encodes a dictionary into a JSON string.
     - parameter dictionary: Dictionary to use to encode JSON string.
     - returns: A JSON string. `nil`, when encoding failed.
     */
    func encode(_ dictionary: [String: Any]) -> String? {
        guard JSONSerialization.isValidJSONObject(dictionary) else {
            assertionFailure("Invalid json object received.")
            return nil
        }

        let jsonObject: NSMutableDictionary = NSMutableDictionary()
        let jsonData: Data

        dictionary.forEach { (arg) in
            jsonObject.setValue(arg.value, forKey: arg.key)
        }

        do {
            jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
        } catch {
            assertionFailure("JSON data creation failed with error: \(error).")
            return nil
        }

        guard let jsonString = String.init(data: jsonData, encoding: String.Encoding.utf8) else {
            assertionFailure("JSON string creation failed.")
            return nil
        }

        print("JSON string: \(jsonString)")
        return jsonString
    }
}

我需要像這樣創建JSON:

Order = {   type_id:'1',model_id:'1',

   transfer:{
     startDate:'10/04/2015 12:45',
     endDate:'10/04/2015 16:00',
     startPoint:'Ул. Момышулы, 45',
     endPoint:'Аэропорт Астаны'
   },
   hourly:{
     startDate:'10/04/2015',
     endDate:'11/04/2015',
     startPoint:'ЖД Вокзал',
     endPoint:'',
     undefined_time:'1'
   },
   custom:{
     startDate:'12/04/2015',
     endDate:'12/04/2015',
     startPoint:'Астана',
     endPoint:'Павлодар',
     customPrice:'50 000'
   },
    commentText:'',
    device_type:'ios'
};

問題是我無法創建有效的JSON。 這是我創建對象的方式:

let jsonObject: [AnyObject]  = [
        ["type_id": singleStructDataOfCar.typeID, "model_id": singleStructDataOfCar.modelID, "transfer": savedDataTransfer, "hourly": savedDataHourly, "custom": savedDataReis, "device_type":"ios"]
    ]

其中savedData是字典:

let savedData: NSDictionary = ["ServiceDataStartDate": singleStructdata.startofWork, 
"ServiceDataAddressOfReq": singleStructdata.addressOfRequest, 
"ServiceDataAddressOfDel": singleStructdata.addressOfDelivery, 
"ServiceDataDetailedText": singleStructdata.detailedText, "ServiceDataPrice": singleStructdata.priceProposed]

當我只使用字符串創建我的JSON對象時,一切正常。 但是當我包含字典時, NSJSONSerialization.isValidJSONObject(value)返回false 。 如何創建有效的字典?


一個問題是此代碼不是Dictionary類型。

let jsonObject: [Any]  = [
    [
         "type_id": singleStructDataOfCar.typeID,
         "model_id": singleStructDataOfCar.modelID, 
         "transfer": savedDataTransfer, 
         "hourly": savedDataHourly, 
         "custom": savedDataReis, 
         "device_type":"iOS"
    ]
]

上面是一個AnyObject ArrayAnyObject有一個類型為[String: AnyObject]Dictionary

嘗試這樣的方法來匹配您在上面提供的JSON:

let savedData = ["Something": 1]

let jsonObject: [String: Any] = [ 
    "type_id": 1,
    "model_id": 1,
    "transfer": [
        "startDate": "10/04/2015 12:45",
        "endDate": "10/04/2015 16:00"
    ],
    "custom": savedData
]

let valid = JSONSerialization.isValidJSONObject(jsonObject) // true

對於Swift 3.0,截至2016年12月,這就是它對我有用的方式:

let jsonObject: NSMutableDictionary = NSMutableDictionary()

jsonObject.setValue(value1, forKey: "b")
jsonObject.setValue(value2, forKey: "p")
jsonObject.setValue(value3, forKey: "o")
jsonObject.setValue(value4, forKey: "s")
jsonObject.setValue(value5, forKey: "r")

let jsonData: NSData

do {
    jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: JSONSerialization.WritingOptions()) as NSData
    let jsonString = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue) as! String
    print("json string = \(jsonString)")                                    

} catch _ {
    print ("JSON Failure")
}

EDIT 2018:我轉向SwiftyJSON以節省時間,讓我的開發生活更輕鬆,更好。 在Swift中本地處理JSON是一種不必要的頭痛和痛苦,加上浪費太多時間,並且創建難以讀寫的代碼,因此容易出現大量錯誤。


查看https://github.com/peheje/JsonSerializerSwift

使用案例:

//Arrange your model classes
class Object {
  var id: Int = 182371823
  }
class Animal: Object {
  var weight: Double = 2.5
  var age: Int = 2
  var name: String? = "An animal"
  }
class Cat: Animal {
  var fur: Bool = true
}

let m = Cat()

//Act
let json = JSONSerializer.toJson(m)

//Assert
let expected = "{\"fur\": true, \"weight\": 2.5, \"age\": 2, \"name\": \"An animal\", \"id\": 182371823}"
stringCompareHelper(json, expected) //returns true

目前支持標準類型,可選標準類型,數組,nullables標準類型數組,自定義類數組,繼承,自定義對象組合。







object