And*_*M16 4 json marshalling go
我正在使用 Golang 构建 REST API,但在尝试正确编组 Json 切片时遇到一些麻烦。即使在网上查看了几个问题和答案之后,我也已经摸不着头脑有一段时间了。
本质上,我有一个Redis客户端,它在调用后调用,并-X GET /todo/吐出一部分todos
[{"content":"test6","id":"46"} {"content":"test5","id":"45"}] //[]string
Run Code Online (Sandbox Code Playgroud)
现在,我想Response根据我todos是否找到的事实返回给定的,所以我有一个Struct喜欢
type Response struct {
Status string
Data []string
}
Run Code Online (Sandbox Code Playgroud)
然后,如果我发现一些todos我只是Marshal一个 json
if(len(todos) > 0){
res := SliceResponse{"Ok", todos}
response, _ = json.Marshal(res)
}
Run Code Online (Sandbox Code Playgroud)
并且,为了删除\响应中不必要的内容,我使用bytes.Replace类似
response = bytes.Replace(response, []byte("\\"), []byte(""), -1)
Run Code Online (Sandbox Code Playgroud)
最后,得到
{
"Status" : "Ok",
"Data" : [
"{"content":"test6","id":"46"}",
"{"content":"test5","id":"45"}"
]
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,每个"之前{和之后的每个}(不包括第一个和最后一个)显然是错误的。虽然正确的 JSON 是
{
"Status": "Ok",
"Data": [{
"content ": "test6",
"id ": "46"
}, {
"content ": "test5",
"id ": "45"
}]
}
Run Code Online (Sandbox Code Playgroud)
我成功地通过找到它们的索引并将它们修剪掉以及使用正则表达式成功地摆脱了它们,但我想知道。
有没有一种干净且更好的方法来实现这一目标?
只要有可能,您就应该从与您所需的 json 匹配的 go 对象中进行编组。我建议从 redis 解析 json:
type Response struct {
Status string
Data []*Info
}
type Info struct {
Content string `json:"content"`
ID string `json:"id"`
}
func main() {
r := &Response{Status: "OK"}
for _, d := range data {
info := &Info{}
json.Unmarshal([]byte(d), info)
//handle error
r.Data = append(r.Data, info)
}
dat, _ := json.Marshal(r)
fmt.Println(string(dat))
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5434 次 |
| 最近记录: |