为了账号安全,请及时绑定邮箱和手机立即绑定

如何解码为嵌入式结构?

如何解码为嵌入式结构?

Go
侃侃尔雅 2022-06-13 16:09:49
我希望能够.Decode()在响应主体上使用来填充结构,而无需首先尝试找出我应该解码为哪种类型的结构。我有一个通用结构Match来保存有关已玩游戏的信息,例如 Fortnite 中的一场比赛。在这个结构中,我MatchData用来保存整个游戏的比赛数据。解码到MatchData结构时,我发现底层嵌入类型已初始化,但具有所有默认值,而不是来自响应的值。type Match struct {    MatchID       int        `json:"match_id"`    GameType      int        `json:"game_type"`    MatchData     *MatchData `json:"match_data"`}type MatchData struct {    MatchGame1    MatchGame2}type MatchGame1 struct {    X int `json:"x"`    Y int `json:"y"`}type MatchGame2 struct {    X int `json:"x"`    Y int `json:"y"`}func populateData(m *Match) (Match, error) {    response, err := http.Get("game1.com/path")    if err != nil {        return nil, err    }        // Here, m.MatchData is set with X and Y equal to 0    // when response contains values > 0    err = json.NewDecoder(response.Body).Decode(&m.MatchData)    if err != nil {        return nil, err    }    return m, nil}编辑 示例预期的 JSON 有效负载。{    "x": 10,    "y": 20}m.GameType我可以通过检查、创建一个对应的结构然后将其分配给来解决这个问题m.MatchData,但是如果我想添加另外 100 个游戏 API,我希望该函数可以与它无关。我不确定这是否可能,但在此先感谢。
查看完整描述

1 回答

?
慕运维8079593

TA贡献1876条经验 获得超5个赞

问题中的方法不起作用,因为嵌入式结构共享字段名称。试试这个方法。


声明一个将游戏类型标识符与相关围棋类型相关联的地图。这只是与解码相关的代码,它知道数百种游戏类型。


var gameTypes = map[int]reflect.Type{

    1: reflect.TypeOf(&MatchGame1{}),

    2: reflect.TypeOf(&MatchGame2{}),

}

将匹配数据解码为原始消息。使用游戏类型创建匹配数据值并解码为该值。


func decodeMatch(r io.Reader) (*Match, error) {


    // Start with match data set to a raw messae.

    var raw json.RawMessage

    m := &Match{MatchData: &raw}


    err := json.NewDecoder(r).Decode(m)

    if err != nil {

        return nil, err

    }


    m.MatchData = nil


    // We are done if there's no raw message.

    if len(raw) == 0 {

        return m, nil

    }


    // Create the required match data value.

    t := gameTypes[m.GameType]

    if t == nil {

        return nil, errors.New("unknown game type")

    }

    m.MatchData = reflect.New(t.Elem()).Interface()


    // Decode the raw message to the match data.

    return m, json.Unmarshal(raw, m.MatchData)


}


查看完整回答
反对 回复 2022-06-13
  • 1 回答
  • 0 关注
  • 165 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号