duanjuelu8874 2018-07-19 12:08
浏览 88
已采纳

在读取json数据时动态识别对象的类型

Quite new to go, sorry if this question sounds obvious.

I would like to use reflection in order to identify the type of an object while reading a json file.

The use case (please see the code below) is the following: I have two structs BoyGift and GirlGift that contain different fields. I have also a Boolean indicator IsBoy that is true if the recipient of the giftis a boy, false otherwise.

The type that encapsulates this behavior is the type Gift:

//Gift type
type Gift struct {
    IsBoy   bool     `json:"isBoy"`
    Payload ??? `json:"payload"`
}

that holds the data. How can I define that type in order the json unmarshal to convert dynamically to the correct type? The "json schema" in this case defines that a Gift should be either a BoyGift or a GirlGift. Is it possible to do this via reflection? How?

Doing unmarshal twice would be great, if the Boolean info is known

package main

import (
    "encoding/json"
    "fmt"
)

//BoyGift type
type BoyGift struct {
    Cars  uint32 `json:"cars"`
    Balls uint32 `json:"balls"`
}

//GirlGift type
type GirlGift struct {
    Dolls uint32 `json:"dolls"`
    Lego  uint32 `json:"lego"`
}

//Gift type
type Gift struct {
    IsBoy   bool     `json:"isBoy"`
    Payload GirlGift `json:"payload"`
}

func main() {

    b := []byte(`{
        "isBoy": true,
        "payload": {
          "cars": 1,
          "balls": 2
        }
      }`)

    var g Gift
    err := json.Unmarshal(b, &g)

    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(g)
}
  • 写回答

1条回答 默认 最新

  • dousha1831 2018-07-19 12:25
    关注

    You should use json.RawMessage to dynamically unmarshal your data.

    You can define Gift's Payliad as json.RawMessage and then delay unmarshaling until you know the value of IsBoy. Below you can find a basic example of how to do it.

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    //BoyGift type
    type BoyGift struct {
        Cars  uint32 `json:"cars"`
        Balls uint32 `json:"balls"`
    }
    
    //GirlGift type
    type GirlGift struct {
        Dolls uint32 `json:"dolls"`
        Lego  uint32 `json:"lego"`
    }
    
    //Gift type
    type Gift struct {
        IsBoy   bool            `json:"isBoy"`
        Payload json.RawMessage `json:"payload"`
    }
    
    func main() {
    
        b1 := []byte(`{
            "isBoy": true,
            "payload": {
              "cars": 1,
              "balls": 2
            }
          }`)
    
        b2 := []byte(`{
            "isBoy": false,
            "payload": {
              "dolls": 3,
              "lego": 4
            }
          }`)
    
        for _, b := range [][]byte{b1, b2} {
            var g Gift
    
            err := json.Unmarshal(b, &g)
            if err != nil {
                fmt.Println(err)
                return
            }
    
            if g.IsBoy {
                var boyGift BoyGift
                err := json.Unmarshal(g.Payload, &boyGift)
                if err != nil {
                    fmt.Println(err)
                    return
                }
                fmt.Println(boyGift)
    
            } else {
                var girlGift GirlGift
                err := json.Unmarshal(g.Payload, &girlGift)
                if err != nil {
                    fmt.Println(err)
                    return
                }
                fmt.Println(girlGift)
    
            }
        }
    
    }
    

    If you want to use Payload as an interface{} (which can be BoyGift or GirlGift), you could create additional helper struct for unmarshalling. Check extended example in Go Playground: https://play.golang.org/p/q1Hn45bgjsc

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘