dsjpqpdm620596 2019-08-28 11:41
浏览 43

我们可以通过反射更新结构字段上的标签吗?

I would like to know if we can update tag on a struct instance before unmarshaling data into it.

type Response struct {
    Name    string          `json:"name"`
    Payload json.RawMessage `json:"default"`
}

var data Response
<update tag on data.Payload to say `json:"id"`>
json.Unmarshal(server_response, &data)

The motivation is to load common keys in Response struct and delegate API specific response to API handler by passing the raw Payload.

The Payload fields, are complex structs, hence being parsed in their own handlers makes it cleaner.

Need to apply the tag, to let json.Unmarshal know which key from server_response to map to Payload.

The metadata fields (like Name) need some validations. So, if I pass the entire response to handler, each handler has to extract each field and return this metadata, which is well, not a very clean approach.

Decoding response to map[string]interface{} also leads to same issue. I want all the fields of metadata in one struct, populated automatically and handler to parse payload. Decoding to generic map, means copying keys.

Example:

type Response struct {
  Version int
  Name string
  Hash string
  Payload json.RawMessage
}

Would like the main function to load the server response in this object, to be able to do all kinds of validations and pass on Payload to handler to let it deal with it.

Using generic map means writing code like: decodedData.Version = genericMap["version"] which does not scale to lots of keys.

  • 写回答

1条回答 默认 最新

  • duanhua9398 2019-08-28 12:37
    关注

    If I understand your question properly, why don't you simply pass the entire response to the handler? The handler will then know if it needs to read from the stats or the id or whatever field... https://play.golang.org/p/pQXa3Gm_WS0 shows roughly the idea.

    An alternative would be to decode your response into a map[string]interface{} and to use https://github.com/mitchellh/mapstructure afterwards to decode parts of the response into structs.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题