在Go语言中,可以将JSON部分反序列化为结构体。

huangapple go评论91阅读模式
英文:

Is it possible to partially deserialise JSON into a struct in go?

问题

我需要与一个返回大量元素的 API 进行集成。

在 Go 的 json 库中,是否可以只选择我想要的字段,还是需要对整个响应进行反序列化?

英文:

I need to integrate with an API that returns loads of elements in its response.

Is it possible to cherry-pick just the fields I want with go's json library or do I need to deserialise the entire response?

答案1

得分: 4

是的。

这是一个示例,其中json中有2个字段,但只解码一个字段:

jsonString := `{"a": 1, "b": 2}`
var rec struct {
	A int `json:"a"`
}
err := json.Unmarshal([]byte(jsonString), &rec)
if err != nil {
	log.Fatalf("json.Unmarshal() failed with '%s'\n", err)
}
fmt.Printf("rec: %+v\n", rec)

运行时输出:

rec: {A:1}

即json中的字段"a"被解码,而字段"b"被丢弃。

完整示例请参见:https://play.golang.org/p/89tu-ZC4pR

英文:

Yes.

Here's an example of having 2 fields in json and only decoding one:

jsonString := `{"a": 1, "b": 2}`
var rec struct {
	A int `json:"a"`
}
err := json.Unmarshal([]byte(jsonString), &rec)
if err != nil {
	log.Fatalf("json.Unmarshal() failed with '%s'\n", err)
}
fmt.Printf("rec: %+v\n", rec)

When run it prints:

rec: {A:1}

i.e. field "a" in json was decoded and field "b" was discarded.

See https://play.golang.org/p/89tu-ZC4pR for full example.

huangapple
  • 本文由 发表于 2017年7月15日 05:07:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/45111605.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定