在JSON中发送null。

huangapple go评论75阅读模式
英文:

Go send null in json

问题

在上面的代码中,我想在我的JSON字符串数组中发送null作为其中一个值。然而,上述代码无法编译,如果我给null添加双引号,它就变成了一个字符串,而不是null值。

在GO中,如何在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..

答案1

得分: 4

为了表示该类型的值为'null',它必须是一个指针。问题不在于不能使用null,而是字符串不能具有该值。这是我在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))
}

正如DaveC提到的,使用指针使初始化变得有点麻烦,但你可以使用我上面提到的相同类型的结构;声明一个字符串,使用&在复合字面量中引用该字符串。

英文:

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.

答案2

得分: 3

你需要使用*string,并创建一个辅助函数来简化操作,类似于以下代码:

func main() {
    chiefTitles := []*string{sP("CEO"), sP("CFO"), nil, sP("CMO")}

    b, _ := json.Marshal(JobTitles{chiefTitles})

    fmt.Println(string(b))
}

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

func sP(s string) *string {
    return &s
}

你可以在playground上运行这段代码。

英文:

You will have to use *string instead, and create a helper function to make it easier, something along the lines of:

func main() {
	chiefTitles := []*string{sP("CEO"), sP("CFO"), nil, sP("CMO")}

	b, _ := json.Marshal(JobTitles{chiefTitles})

	fmt.Println(string(b))
}

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

func sP(s string) *string {
	return &s
}

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2015年9月5日 03:45:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/32405499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定