Create JSON in swift

前端 未结 6 1230
眼角桃花
眼角桃花 2020-12-07 23:03

I need to create JSON like this:

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

   transfer:{
     startDate:\'10/04/2015 12:45\',
     endDate:\'10/04/2015 16:0         


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 23:48

    • Swift 4.1, April 2018

    Here is a more general approach that can be used to create a JSON string by using values from a dictionary:

    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
        }
    }
    

    How to use it:

    let exampleDict: [String: Any] = [
            "Key1" : "stringValue",         // type: String
            "Key2" : boolValue,             // type: Bool
            "Key3" : intValue,              // type: Int
            "Key4" : customTypeInstance,    // type: e.g. struct Person: Codable {...}
            "Key5" : customClassInstance,   // type: e.g. class Human: NSObject, NSCoding {...}
            // ... 
        ]
    
        if let jsonString = JSONStringEncoder().encode(exampleDict) {
            // Successfully created JSON string.
            // ... 
        } else {
            // Failed creating JSON string.
            // ...
        }
    

    Note: If you are adding instances of your custom types (structs) into the dictionary make sure your types conform to the Codable protocol and if you are adding objects of your custom classes into the dictionary make sure your classes inherit from NSObject and conform to the NSCoding protocol.

提交回复
热议问题