[英]Convert swift struct to json string
I am trying to convert my swift struct to json format. 我正在尝试将我的swift结构转换为json格式。 There seems to be quite a few questions like this, but none of the solutions has worked for me so far.
似乎有很多这样的问题,但是到目前为止,没有一种解决方案对我有用。
Here is my struct 这是我的结构
struct Rec : Codable {
var name:String
var time:Int
var values:[String]
var jsonRepresentation : String {
return """
{
"name":"\(name)",
"time":\(time),
"values":\(values)
}
"""
}
}
Here is the json format that the external api recieves. 这是外部api接收的json格式。
{
"op" : "delete",
"rec": {
"name" : "some string",
"time":200,
"values": [
"127.0.0.1"
]
}
}
Here is my function the creates the HTTP request 这是我创建HTTP请求的函数
private func createPatchRequest(op: String, url: URL, rec: Rec) throws -> URLRequest {
let dictionary: [String: String] = [
"op":op,
"rec":rec.jsonRepresentation
]
let jsonData = try JSONEncoder().encode(dictionary)
var request = URLRequest(url: url)
request.httpMethod = "PATCH"
request.httpBody = jsonData
request.addValue("application/json", forHTTPHeaderField:"Content-Type")
return request
}
I always get a 400 and i believe that swift isn't' encoding my json properly. 我总是得到400,我相信swift不能正确编码我的json。 I tried the request on postman and it worked fine!
我在邮递员上尝试了该请求,效果很好!
Here is how it looked on postman 这是邮递员的样子
{
"op" : "delete",
"rec": {
"name" : "some string",
"time":600,
"values": [
"127.0.0.1"
]
}
}
Any ideas? 有任何想法吗? Thanks!
谢谢!
The problem is that the API expects rec
to be a JSON object, but you're sending Rec as a string representation of a JSON Object. 问题在于该API期望
rec
是一个JSON对象,但是您正在将Rec作为JSON对象的字符串表示形式发送。 ie This is the JSON that you're sending: 即这是您要发送的JSON:
{
"rec": "{\n\"name\":\"some string\",\n\"time\":1,\n\"values\":[\"127.0.0.1\"]\n}",
"op": "delete"
}
The ideal approach would be to create a Codable
PatchRequest
with a nested Rec
struct and encode that. 理想的方法是使用嵌套的
Rec
结构创建一个Codable
PatchRequest
并对其进行编码。 You can try the following snippet on Playground 您可以在Playground上尝试以下代码段
struct Rec : Codable {
var name:String
var time:Int
var values:[String]
}
struct PatchRequest : Codable{
var op: String
var rec: Rec
}
let rec = Rec(name: "some string",time: 600,values: ["127.0.0.1"])
let requst = PatchRequest(op: "delete",rec: rec)
let jsonData = try JSONEncoder().encode(requst)
let jsonString = String(data: jsonData, encoding: .utf8)
This has the added benefit of reducing the number of parameters required by your API method and making the code cleaner overall: 这具有减少API方法所需的参数数量以及使代码整体更整洁的额外好处:
private func createPatchRequest(url: URL, patchRequest: PatchReuest) throws -> URLRequest {
let jsonData = try JSONEncoder().encode(patchRequest)
var request = URLRequest(url: url)
request.httpMethod = "PATCH"
request.httpBody = jsonData
request.addValue("application/json", forHTTPHeaderField:"Content-Type")
return request
}
Lastly, I would recommend using let
in your structs instead of var
unless it's absolutely necessary. 最后,除非绝对必要,否则我建议在您的结构中使用
let
而不是var
。
Your jsonRepresentation is a string but should be a dictionary . 您的jsonRepresentation是一个字符串,但应该是一个字典 。 Update your struct this way:
通过以下方式更新您的结构:
struct Rec : Codable {
var name:String
var time:Int
var values:[String]
var jsonRepresentation: [String: Any] {
return [
"name": name,
"time": time,
"values": values
]
}
}
Hope it helps! 希望能帮助到你! Please let me know if it worked.
请让我知道它是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.