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

在读取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

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

报告相同问题?