简体   繁体   中英

Converting struct to a JSON string in Swift

I am trying to convert a simple struct to JSON string. The struct looks like this:

struct MyStruct: Equatable {

let propertyA:Int
let propertyB:String
let propertyC:Double
//There are about ten more fields

func myStructMethod->String{
    return "return value"
    }
}

So, because the struct doesn't conform to AnyObject type (but rather to Any I guess) the simple conversion like this fails:

let data = try NSJSONSerialization.dataWithJSONObject(myStructArray, options: nil)
let string = NSString(data: data!, encoding: NSUTF8StringEncoding)

Is there some way to skip creating JSON string "by the hand" (say using array map and building string by myself)?

There is no such thing as a "JSON string". JSON documents are data.

JSON objects are strings, numbers, booleans, null values, arrays of JSON objects, dictionaries with string keys and JSON objects as values.

You convert anything you have into such a dictionary or array, then use NSJSONSerialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM