Pircate / CleanJSON

Swift JSON decoder for Codable
MIT License
292 stars 40 forks source link

model转json字符串,怎么办呢 #19

Closed OneTaoist closed 3 years ago

OneTaoist commented 3 years ago

比如说有些时候,需要把接口数据本地化:把模型数组转成字符串存到本地文件或数据库中

Pircate commented 3 years ago

public extension Encodable {

@inline(__always)
func toJSON(using encoder: JSONEncoder = .init()) throws -> Data {
    return try encoder.encode(self)
}

@inline(__always)
func toJSONString(using encoder: JSONEncoder = .init()) -> String? {
    guard let data = try? toJSON(using: encoder) else { return nil }

    return String(data: data, encoding: .utf8)
}

}

可以使用这两个函数

OneTaoist commented 3 years ago

@Pircate ok