qq316107934
V2EX  ›  问与答

一个棘手的问题, golang 怎样才能动态增删 JSON 返回字段?

  •  
  •   qq316107934 · Oct 10, 2018 · 2636 views
    This topic created in 2776 days ago, the information mentioned may be changed or developed.

    迫于需求需要在返回参数里面根据条件判断是否多加一个字段。 目前的手段:

    type struct1 struct{
     xxxx int
    }
    
    type struct2 struct{
     additional_info string
    }
    
    func xxx(){
       var data interface{} 
       if(condition){
          data = struct1{}
       }else{
          data=  struct2{}
       }
       data.xxxx=123
    }
    

    到最后一行会报 data.xxxx undefined (type interface {} is interface with no methods)错误。

    请问 golang 有办法使用类型重载或者增删 JSON 字段么?感谢!最好能兼顾效率。

    Supplement 1  ·  Oct 10, 2018
    蠢了:解决方案很简单,用 omitempty
    7 replies    2018-10-10 20:23:01 +08:00
    qq316107934
        1
    qq316107934  
    OP
       Oct 10, 2018 via Android
    自己顶一下,这种编译型语言很无解呀
    misaka19000
        2
    misaka19000  
       Oct 10, 2018 via Android
    用 map 不行吗?
    qq316107934
        3
    qq316107934  
    OP
       Oct 10, 2018
    @misaka19000 #2 struct 是 json unmarshal 出来的,不行,struct 转 map 再处理反射效率太低了,对并发有影响
    cin
        4
    cin  
       Oct 10, 2018   ❤️ 1
    type struct1 struct{
    xxxx int `json:"xxxx, omitempty"`
    }
    tag 加上 omitempty ?
    cloverstd
        5
    cloverstd  
       Oct 10, 2018 via iPhone
    SetXxxx
    unavph
        6
    unavph  
       Oct 10, 2018 via iPhone   ❤️ 1
    直接加在 struct1 里 omitempty 不行么?
    qq316107934
        7
    qq316107934  
    OP
       Oct 10, 2018
    @cin #4
    @unavph #6
    感觉正解了!感谢!!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1061 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 58ms · UTC 18:12 · PVG 02:12 · LAX 11:12 · JFK 14:12
    ♥ Do have faith in what you're doing.