douchuang4181 2018-06-04 08:11
浏览 30
已采纳

将结构编组为json时在字段上执行操作

I have the following struct:

type Message struct {
    DoubleMe    int     `json:"double_me"`
    Message     string  `json:"message"`
}

And a instance of it:

m := Message{5, "Hello, World!"}

My goal is to perform some operation to the DoubleMe field when it's marshaled to json, for example doubling it. So the output would be:

{"double_me":10,"message":"Hello, World!"}

How can I achieve this?

  • 写回答

1条回答 默认 最新

  • dongliaojing0554 2018-06-04 08:18
    关注

    Implement json.Marshaler on your struct, which is to define a custom marshaling logic, which may double the DoubleMe field.

    See this example:

    type Message struct {
        DoubleMe int    `json:"double_me"`
        Message  string `json:"message"`
    }
    
    func (m Message) MarshalJSON() ([]byte, error) {
        m.DoubleMe *= 2
    
        type Message2 Message
        return json.Marshal(Message2(m))
    }
    
    func main() {
        m := Message{5, "Hello, World!"}
        data, err := json.Marshal(m)
        fmt.Println(string(data), err)
        fmt.Println("Original:", m)
    }
    

    Output (try it on the Go Playground):

    {"double_me":10,"message":"Hello, World!"} <nil>
    Original: {5 Hello, World!}
    

    Some notes:

    • If you need this to work backwards too (e.g. when unmarshaling, divide the value by 2), also implement json.Unmarshaler (left to the reader as an exercise).

    • Even though we doubled the field, after the marshaling, the original value did not change. This is because the method has a non-pointer receiver, so inside the method only a copy is acquired and modified, but not the original value. If we would've used pointer receiver, we would have to take care of restoring it.

    • Also note that a new type Message2 is created and used inside the MarshalJSON() method. This is because we also used the json package to do the "usual" marshaling once we applied our custom logic. But if we would pass m to json.Marshal(), that would be an endless "recursion", because the json package would again call this MarshalJSON() method. Instead we created a Message2 type having Message as its underlying type. This means Message2 has zero methods (it does not implement json.Marshaler), so passing a value of Message2 to json.Marshal() will not call this method again, and since it has Message as its underlying type, we can simply convert a value of type Message to Message2.

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

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line