json - 使用 "valid"零值解码 JSON

标签 json pointers go unmarshalling

我有一些 JSON,我正在将其解码为各种结构,以便我可以处理数据,看来这正在变成项目中最难的部分!!!

此 JSON 的格式是,如果缺少该字段,则它基本上为 nil。这是 Default struct values 的后续,但认为它应该在 SO 上提出自己的问题。

因此,零是一个有效值,我需要能够在我的 Go 代码中辨别它。有没有办法让 Go 用指针解码到这个结构中?

在示例 playground 中,您可以明白我的意思,它“似乎”可以工作,但是当我打印出其中一个指针值时,它总是打印指针地址而不是实际值。

package main

import "fmt"
import "log"
import "encoding/json"

const inputMissing = `
["AAAAAA", {"testCode" : "Sss"}, 123456]
`

const inputZero = `
["AAAAAA", {"testCode" : "Sss", "missingInt" : 0, "defaultInt" : 0,"missingString" : "", "defaultString" : ""}, 123456]
`

type RawMessage struct {
    AlwaysString  string
    ClientData    ClientData
    ReceptionTime int
}

type ClientData struct {
    TestCode   string
    MissingInt *int
    DefaultInt int

    MissingString *string
    DefaultString string
}

func main() {

    var n RawMessage
    if err := json.Unmarshal([]byte(inputMissing), &n); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%#v\n", n)

    var o RawMessage
    if err := json.Unmarshal([]byte(inputZero), &o); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%#v\n", o)

    fmt.Printf("Should print the value of the int, not pointer... %i", o.ClientData.MissingInt)
}

func (n *RawMessage) UnmarshalJSON(buf []byte) error {
    tmp := []interface{}{&n.AlwaysString, &n.ClientData, &n.ReceptionTime}
    wantLen := len(tmp)
    if err := json.Unmarshal(buf, &tmp); err != nil {
        return err
    }
    if g, e := len(tmp), wantLen; g != e {
        return fmt.Errorf("wrong number of fields in RawMessage: %d != %d", g, e)
    }
    return nil
}

最佳答案

您的代码是正确的。针对 nil 测试指针并在需要值时取消引用指针:

fmt.Printf("Should print the value of the int, not pointer... %d", *o.ClientData.MissingInt)

关于json - 使用 "valid"零值解码 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40971542/

相关文章:

javascript - 修复无效 JSON 的最有效方法

c - 如何从一个指针的地址中减去另一个指针的地址?

java - 如何在递归函数的每一级都有一个新的局部数组

mongodb - 在 Golang 的两个不同结构字段中映射 Mongo _id

go - 如何在不使用迭代器的情况下在 Golang 中循环?

javascript - 来自 localStorage 问题的 JSON.parse()

javascript - 如何使用另一个带下划线的数组中的元素过滤数组?

json - 反转 JSON 请求的输出

C - 跨多个文件返回结构指针时出错

go - 如何从自身调用链码函数来记录子交易