处理包含 null 值的 JSON 响应
时间:2024-03-08
浏览:383
作者:佚名
一分耕耘,一分收获!既然打开了这篇文章《处理包含 null 值的 JSON 响应》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!
问题内容
我对 go 中 json null 值的处理感到困惑。 假设我有以下示例:
package main
import (
"fmt"
"encoding/json"
"log"
)
type Fruit struct {
Name string
Price int
Owner string
}
func main() {
jsonData := []byte(`
{
"Name": "Standard",
"Price" : null,
"Owner": null
}`)
var f Fruit
err := json.Unmarshal(jsonData, &f)
if err != nil {
log.Println(err)
}
fmt.Printf("Name is : %s\nPrice is : %d\nOwner is : %s\n", f.Name, f.Price, f.Owner)
if f.Owner == "" {
fmt.Printf("Name should be nil?\n")
}
if f.Price == 0 {
fmt.Printf("Price should be nil?\n")
}
}
现在,我的主要问题是:
区分 nil 值和默认值的正确方法是什么?
例如,在下面的示例中,我无法知道水果的价格是否尚未设定或实际价格为零。
大家如何处理这个问题?
在其他语言中,字符串和整数都可以为 null,但 go 中并非如此。
解决方案
使用指针:
type Fruit struct {
Name *string `json:"Name,omitempty"`
Price *int `json:"Price,omitempty"`
Owner *string `json:"Owner,omitempty"`
}
然后你可以检查一个字段是否为零,或者是否有值。
但是,如果您想区分文档中存在字段并设置为 null 的情况和该字段根本不存在的情况,这对您没有帮助。
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
12.01
热门专题
