为了账号安全,请及时绑定邮箱和手机立即绑定

如何在一个字段中创建具有 nil 值的映射,然后将其编组为 json?

如何在一个字段中创建具有 nil 值的映射,然后将其编组为 json?

Go
幕布斯7119047 2023-06-19 16:11:43
我需要获取 json 字符串{"Error": null }我可以使用这种方法来做到这一点type OKResponse struct {    Error *int `json:"Error"`}encoded, err := json.Marshal(OKResponse{})...我如何使用地图获得相同的结果?或者这是不可能的?例如这样的事情jsonbody := map[string]int{"Error": nil}encoded, err := json.Marshal(&jsonbody)...
查看完整描述

3 回答

?
万千封印

TA贡献1891条经验 获得超3个赞

对于这种特殊情况,您可以使用:

jsonbody := map[string]error{"Error": nil}

但对于更一般化的情况,您还可以使用:

jsonbody := map[string]interface{}{"Error": nil}

两种方法都会产生:

{"Error":null}


查看完整回答
反对 回复 2023-06-19
?
Cats萌萌

TA贡献1805条经验 获得超9个赞

如果将类型更改为*int,它将执行您想要的操作:


type OKResponse struct {

    Error *int `json:"Error"`

}

例子:


r1 := OKResponse{}

result1, _ := json.Marshal(r1)

fmt.Printf("result1 = %s\n", string(result1))


errNo := 1

r2 := OKResponse{Error: &errNo}

result2, _ := json.Marshal(r2)

fmt.Printf("result2 = %s\n", string(result2))

输出:


result1 = {"Error":null}

result2 = {"Error":1}

在操场上看到它。



查看完整回答
反对 回复 2023-06-19
?
阿晨1998

TA贡献2037条经验 获得超6个赞

由于 number 无法获得nil值,因此您不能那样做。


您可以做的是使用指针类型,然后就可以完成,例如:


package main


import (

    "fmt"

    "encoding/json"

)


func main() {

    jsonbody := map[string]*int{"Error": nil}

    encoded, _ := json.Marshal(&jsonbody)

    fmt.Printf("%s", encoded)


    num := 6

    jsonbody = map[string]*int{"Error": &num}

    encoded, _ = json.Marshal(&jsonbody)

    fmt.Printf("%s", encoded)

}

https://play.golang.org/p/TTpgr7Cy17C


查看完整回答
反对 回复 2023-06-19
  • 3 回答
  • 0 关注
  • 100 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信