Give the Encodable extension a toJSONString() method
public extension Encodable {
func toJSONString() -> String {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
guard let data = try? encoder.encode(self) else{ return "" }
guard let jsonStr = String(data: data, encoding: .utf8) else{ return "" }
return jsonStr
}
}
Copy the code
Create a model that follows the Codable(Decodable & Encodable) protocol
struct TestModel: Codable {
var name: String = ""
var age: Int = 0
}
Copy the code
Use:
let testModel = TestModel(name: "name1", age: 10)
debugPrint(testModel.toJSONString())
Copy the code
Output:
"{\"name\":\"name1\",\"age\":10}"
Copy the code