英文:
Unmarshall json reference types
问题
我正在尝试编写一个可工作的示例来测试“Reference Types”部分,链接如下:这个链接。
但是我无法理解这应该如何工作。我尝试编写的示例如下,仅供参考:
package main
import (
"fmt"
"log"
"encoding/json"
)
type Foo1 struct {
Val int
}
type Foo2 struct {
Name string
}
type IncomingMsg struct {
F1 *Foo1
F2 *Foo2
}
func main() {
b := []byte(`{"F1" : {"Val":13}}`)
// b := []byte(`{"F2" : {"Name":"Hello"}}`)
var msg IncomingMsg
err := json.Unmarshal(b, &msg)
if err != nil {
log.Fatal(err)
}
if msg.F1 != nil {
fmt.Println(msg.F1.Val)
}
if msg.F2 != nil {
fmt.Println(msg.F2.Name)
}
}
有经验的Go开发者能帮助解决这个问题吗?
编辑:提供的测试已更新,现在按预期工作。感谢Adam先生提供的答案,它帮助我很多理解了这个问题!
英文:
I'm trying to write a working example to test "Reference Types" section of this link.
But I'm unable to understand how this should work. The example I'm trying to write without success is provided below, just for reference:
package main
import (
"fmt"
"log"
"encoding/json"
)
type Foo1 struct {
Val int
}
type Foo2 struct {
Name string
}
type IncomingMsg struct {
F1 *Foo1
F2 *Foo2
}
func main() {
b := []byte(`{"F1" : {"Val":13}}`)
// b := []byte(`{"F2" : {"Name":"Hello"}}`)
var msg IncomingMsg
err := json.Unmarshal(b, &msg)
if err != nil {
log.Fatal(err)
}
if msg.F1 != nil {
fmt.Println(msg.F1.Val)
}
if msg.F2 != nil {
fmt.Println(msg.F2.Name)
}
}
Can some of you with more experience with Go help with this issue?
EDIT: The provided test has been updated, now is working as expected. Thank you Mr Adam for the answer provided, it helped me a lot to understand this issue!
答案1
得分: 3
你在示例中发布的 JSON 看起来在 body 中缺少 F1
?
https://play.golang.org/p/Fl-lhH2y3X
b := []byte(`{"F1":{"Val":13}}`)
英文:
The json you have posted in your example looks like it is missing F1
in the body?
https://play.golang.org/p/Fl-lhH2y3X
b := []byte(`{"F1":{"Val":13}}`)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论