如何将模型对象转换为 JSON - Swift 4
Posted
技术标签:
【中文标题】如何将模型对象转换为 JSON - Swift 4【英文标题】:How to Convert a model object into JSON - Swift 4 【发布时间】:2018-01-25 05:28:38 【问题描述】:如何将模型对象转换为 JSON? 我想要“Answer”对象。
// 答案类
class Answers
var cat_id: String!
var responses = [Response]()
var date: String!
var comment: String!
var time: String!
var lat: String!
var lon: String!
var address: String!
// 响应类
class Response
var que_id: String!
var question: String!
var response: String!
【问题讨论】:
How to serialize or convert Swift objects to JSON?的可能重复 试试这个:***.com/a/10548511/5167909 不相关但 NEVER 将类中的属性声明为隐式未包装的选项,作为不编写初始化程序的不在场证明。属性应该是可选的,然后将它们声明为常规可选(?
),否则声明为非可选(无问号和感叹号)
【参考方案1】:
使两种类型都符合Codable
:
class Answers: Codable
...
class Response: Codable
...
然后使用JSONEncoder
:
let answers: Answers = ...
do
let data = try JSONEncoder().encode(answers)
// use data here
catch
print(error)
见Encoding and Decoding Custom Types。
【讨论】:
【参考方案2】:如果您使用的是 swift4,您可以使用可编码和可解码协议。我仍在处理异构对象列表。但这应该对你有用。让你的类符合ABEncodable
。
protocol ABDecodable: Decodable
static func decodeFromData(_ data: Data) -> Decodable?
protocol ABEncodable: Encodable
static func encodeFromObject<T>(_ object: T) -> Data? where T: Encodable
extension ABDecodable
static func decodeFromData(_ data: Data) -> Decodable?
do
return try JSONDecoder().decode(self, from: data)
catch
print(error)
return nil
extension ABEncodable
static func encodeFromObject<T>(_ object: T) -> Data? where T: Encodable
do
return try JSONEncoder().encode(object)
catch
return nil
//MARK: Decode mapper class
//Send jsonString or data to decode it into an required Object
final class Decode<T: Decodable>
private func decodeData(_ data: Data) -> T?
if let klass = T.self as? ABDecodable.Type
if let object = klass.decodeFromData(data) as? T
return object
else
do
return try JSONDecoder().decode(T.self, from: data)
catch
print(error)
return nil
func fromJsonString(_ json: String) -> T?
guard let data = json.data(using: String.Encoding.utf8) else return nil
if let object = decodeData(data)
return object
return nil
func fromData(_ data: Data) -> T?
if let object = decodeData(data)
return object
return nil
//MARK: Encode mapper class
//Send jsonString or data to decode it into an required Object
final class Encode<N:Encodable>
private func encodeObject(_ object: N) -> Data?
if let klass = N.self as? ABEncodable.Type
if let data = klass.encodeFromObject(object)
return data
else
do
return try JSONEncoder().encode(object)
catch
print(error)
return nil
func toJsonString(_ object: N) -> String?
if let data = encodeObject(object)
return String(data: data, encoding: .utf8)
return nil
func toData(_ object: N) -> Data?
if let data = encodeObject(object)
return data
return nil
【讨论】:
以上是关于如何将模型对象转换为 JSON - Swift 4的主要内容,如果未能解决你的问题,请参考以下文章
如何将 json 数据从 alamofire 转换为 swift 对象
如何在 xcode (swift) 中从 Json Schema / Json 生成模型对象?
Swift:如何将带有 Alamofilre 或 SwiftyJSON 的 JSON 字符串转换为 ObjectMapper?