[英]In Go, how to unmarshal a string containing an array of a struct
One of the attributes that I'm receiving from an API is a string containing an array of a struct, where the attributes of the struct are escaped.我从 API 接收的属性之一是包含结构数组的字符串,其中结构的属性被转义。
I would like data (the output object) to be a simple array of MyStruct like this:我希望数据(输出对象)是一个简单的 MyStruct 数组,如下所示:
[{"f":"f-val"}] [{"f":"f-val"}]
However, the output that I get is an empty array [].但是,我得到的输出是一个空数组 []。
Can someone please help?有人可以帮忙吗? I'd be really grateful.我真的很感激。
package main
import "fmt"
import "encoding/json"
type MyStruct struct {
F string
}
func main() {
stringResponse := `"[{\"f\":\"f-val\"}]"`
var data []MyStruct
json.Unmarshal([]byte(string(stringResponse)), &data)
fmt.Print(data)
}
Here is proper example:这是正确的例子:
package main
import (
"encoding/json"
"strconv"
)
func main() {
s, e := strconv.Unquote(`"[{\"f\":\"f-val\"}]"`)
if e != nil {
panic(e)
}
var (
b = []byte(s)
m []struct{F string}
)
json.Unmarshal(b, &m)
println(m[0].F == "f-val")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.