dsen53898 2015-09-04 19:45
浏览 128
已采纳

在json中发送null

type JobTitles struct {
    Titles []string `json:"titles"`
}

chiefTitles := []string{"CEO", "CFO", null, "CMO"}

jsonOut := JobTitles{chiefTitles}

In the code above, I would like to be able to send null as one of the values in my json string array. However, the above will not compile and if I add double quotes to null it becomes a string not the value null.

How can I send null in my json response in GO?

This article seems to help, but looks to be the inverse of my question..

  • 写回答

2条回答 默认 最新

  • duanhanzi8328 2015-09-04 19:53
    关注

    In order to represent that type with the value 'null' it would have to be a pointer. The problem isn't that you can't use null but rather that a string can't have that value. Here is a quick example I made in the playground; https://play.golang.org/p/SXO5sBl2mR

    package main
    
    import "fmt"
    import "encoding/json"
    
    type Test struct {
        A *string
        B *string
    }
    
    func main() {
            s := "Something"
            t := Test{A:&s, B:nil}
            b, err := json.Marshal(t)
            if err != nil {
                fmt.Println(err)
            }
        fmt.Println(string(b))
    }
    

    As DaveC mentioned using pointers makers the initilization a bit more cumbersome but you can use the same type of constructs I have above; declare a string, use the & that string in the composite literal.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题