微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

解析带有空字符串字段的 JSON

如何解决解析带有空字符串字段的 JSON

我需要将 JSON 解析为 Go 结构体。以下是结构

type Replacement struct {
Find        string `json:"find"`
ReplaceWith string `json:"replaceWith"`
}

以下是 json 示例:

{
"find":"TestValue","replaceWith":""
}

输入 json 的某些字段可以有空值。 Go 的 encoding/json认为 JSON 中提供的任何空字符串采用 nil 值。 我有一个下游服务,它查找并替换配置中的 replaceWith 值。这会导致我的下游服务出现问题,因为它不接受 nil 参数的 replaceWith我有一个解决方法,用 nil 替换 "''" 值,但这可能会导致某些值被替换为 '' 的问题。有没有办法让 json not 将空字符串解析为 nil 而只是 ""

这是代码链接https://play.golang.org/p/SprPz7mnWR6

解决方法

在 Go 中,字符串类型不能保存 nil 值,它是指针、接口、映射、切片、通道和函数类型的零值,表示未初始化的值。

当您在示例中将 JSON 数据解组为 struct 时,ReplaceWith 字段确实是一个空字符串 ("") - 这正是您所要求的。

type Replacement struct {
    Find        string `json:"find"`
    ReplaceWith string `json:"replaceWith"`
}

func main() {
    data := []byte(`
    {
           "find":"TestValue","replaceWith":""
    }`)
    var marshaledData Replacement
    err := json.Unmarshal(data,&marshaledData)
    if err != nil {
        fmt.Println(err)
    }
    if marshaledData.ReplaceWith == "" {
        fmt.Println("ReplaceWith equals to an empty string")
    }
}
,

您可以在字符串中使用指针,如果 JSON 中缺少该值,那么它将为零。我过去也这样做过,但目前我没有代码。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。