简体   繁体   English

在Swift中将结构转换为JSON字符串

[英]Converting struct to a JSON string in Swift

I am trying to convert a simple struct to JSON string. 我正在尝试将简单的结构转换为JSON字符串。 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: 所以,这是因为结构不符合AnyObject型(而是Any这样的失败,我猜测)的简单的换算:

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)? 有什么方法可以跳过“手工”创建JSON字符串的操作(例如使用数组映射和自己构建字符串)吗?

There is no such thing as a "JSON string". 没有“ JSON字符串”之类的东西。 JSON documents are data. JSON文档是数据。

JSON objects are strings, numbers, booleans, null values, arrays of JSON objects, dictionaries with string keys and JSON objects as values. JSON对象是字符串,数字,布尔值,空值,JSON对象数组,以字符串键和JSON对象作为值的字典。

You convert anything you have into such a dictionary or array, then use NSJSONSerialization. 您可以将任何东西转换成这样的字典或数组,然后使用NSJSONSerialization。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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