Create JSON in swift

前端 未结 6 1216
眼角桃花
眼角桃花 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:26

    Creating a JSON String:

    let para:NSMutableDictionary = NSMutableDictionary()
    para.setValue("bidder", forKey: "username")
    para.setValue("day303", forKey: "password")
    para.setValue("authetication", forKey: "action")
    let jsonData = try! NSJSONSerialization.dataWithJSONObject(para, options: NSJSONWritingOptions.allZeros)
    let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
    print(jsonString)
    
    0 讨论(0)
  • 2020-12-07 23:33

    One problem is that this code is not of type Dictionary.

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

    The above is an Array of AnyObject with a Dictionary of type [String: AnyObject] inside of it.

    Try something like this to match the JSON you provided above:

    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
    
    0 讨论(0)
  • 2020-12-07 23:41

    For Swift 3.0, as of December 2016, this is how it worked for me:

    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: I now use SwiftyJSON library to save time and make my development life easier and better. Dealing with JSON natively in Swift is an unnecessary headache and pain, plus wastes too much time, and creates code which is hard to read and write, and hence prone to lots of errors.

    0 讨论(0)
  • 2020-12-07 23:42

    This worked for me... Swift 2

    static func checkUsernameAndPassword(username: String, password: String) -> String?{
        let para:NSMutableDictionary = NSMutableDictionary()
            para.setValue("demo", forKey: "username")
            para.setValue("demo", forKey: "password")
           // let jsonError: NSError?
        let jsonData: NSData
        do{
            jsonData = try NSJSONSerialization.dataWithJSONObject(para, options: NSJSONWritingOptions())
            let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
            print("json string = \(jsonString)")
            return jsonString
    
        } catch _ {
            print ("UH OOO")
            return nil
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 23:49

    Check out https://github.com/peheje/JsonSerializerSwift

    Use case:

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

    Currently supports standard types, optional standard types, arrays, arrays of nullables standard types, array of custom classes, inheritance, composition of custom objects.

    0 讨论(0)
提交回复
热议问题