解析 JSON 引用类型

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

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先生提供的答案,它帮助我很多理解了这个问题! 解析 JSON 引用类型

英文:

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! 解析 JSON 引用类型

答案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}}`)

huangapple
  • 本文由 发表于 2017年5月30日 15:48:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/44256484.html
匿名

发表评论

匿名网友

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

确定