我有一些 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/