duan0821 2017-06-22 08:00
浏览 40
已采纳

具有非简单类型的GoLang JSON元帅不完全-可以避免使用指针吗?

Code below is the explanation. The only way I can get omitempty to work with non-simple types is to make that type a pointer.

Is there an alternative solution to this by not using pointers?

CODE NOT WORKING:

type Foo struct {
    Bar Bar `json:"bar,omitempty"`
}

type Bar struct {
    Baz string `json:"baz"`
}

func main() {

    foo := Foo{}

    jsonBytes, _ := json.Marshal(foo)

    fmt.Printf("%s
", jsonBytes)
}

OUTPUT: {"bar":{"baz":""}}

CODE WORKING, BUT NOT WHAT I WANT:

type Foo struct {
    Bar *Bar `json:"bar,omitempty"`
}

type Bar struct {
    Baz string `json:"baz"`
}

func main() {

    foo := Foo{}

    jsonBytes, _ := json.Marshal(foo)

    fmt.Printf("%s
", jsonBytes)
}

OUTPUT: {}

  • 写回答

1条回答 默认 最新

  • duanken7168 2017-06-22 08:14
    关注

    Is there an alternative solution to this by not using pointers?

    No.

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

报告相同问题?

悬赏问题

  • ¥15 CATIA有些零件打开直接单机确定终止
  • ¥15 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址