Converting Object to JSON String For POST Request

2019-08-13 12:07发布

问题:

I have an object that is an instance of a class similar to this:

class MyClass {
    let aString: String
    let bString: String
    var cArray = [AnotherClass]()

    init etc...
}

AnotherClass is something like:

class AnotherClass {
    let aInt: Int
    let bInt: Int
    var cFloat = Float

    init etc...
}

Ok, now i need to pass that object (instance of MyClass) as a POST request string parameter with the following format:

 {
     "aString": "1",
     "bString": "yannis",
     "cArray": [
       {
         "aInt": 1965887,
         "bInt": 36513032311523,
         "cFloat": 1.0
       },
       {
         "aInt": 1916915,
         "bInt": 360397932121597,
         "cFloat": 1.0
       }
     ]
 }

Any ideas how to achieve this? I'm using Swift 1.2 (and SwiftyJSON, if that helps) Thanks!

回答1:

You'll need to convert both objects into Dictionaries by adding a function like:

func convertToDictionary() -> Dictionary<String, AnyObject> {

    return [
        "aString": self.aString,
        "bString": self.bString,
        "cArray": self.cArray
    ]
}

to both classes.

Then serialize it using:

let theJSONData = NSJSONSerialization.dataWithJSONObject(
  dictionary ,
  options: NSJSONWritingOptions(0),
  error: nil)

Where dictionary is something like dictionary = myClass.convertToDictionary

Maybe even serialize the nested objects in the Array for MyClass before serializing the MyClass object as well.



回答2:

First of all, as far I know SwiftyJSON not support Object Mapping to JSON, it's only for parse JSON object retrieved from some source.

If you need to make Object Mapping to JSON there are some nice libraries you can use like the two following :

  • ObjectMapper
  • swift-serializer

The documentation of both are very easy to follow. But if you don't need to create a very complex JSON from a very complex class, you can handle it yourself with some method to map your object to JSON and with the help of the class NSJSONSerialization you can validate your creation before use it. You can learn a lot from make the mapping yourself in the Strong Type Object Serialization to JSON (Nerd Alert) article.

I hope this help you.