gpt4 book ai didi

json - 如何为从 Go 中的标量派生的类型实现 UnmarshalJSON?

转载 作者:数据小太阳 更新时间:2023-10-29 03:27:52 27 4
gpt4 key购买 nike

我有一个简单的类型,它在 Go 中实现了子类型整数常量到字符串的转换,反之亦然。我希望能够自动将 JSON 中的字符串解码为这种类型的值。我不能,因为 UnmarshalJSON 没有给我返回或修改标量值的方法。它需要一个结构,其成员由 UnmarshalJSON 设置。除了内置标量类型,“,string”方法也不起作用。有没有办法为派生的标量类型正确实现 UnmarshalJSON?

这是我所追求的一个例子。我希望它打印四次“Hello Ralph”,但它打印了四次“Hello Bob”,因为 PersonID 没有被更改。

package main

import (
"encoding/json"
"fmt"
)

type PersonID int

const (
Bob PersonID = iota
Jane
Ralph
Nobody = -1
)

var nameMap = map[string]PersonID{
"Bob": Bob,
"Jane": Jane,
"Ralph": Ralph,
"Nobody": Nobody,
}

var idMap = map[PersonID]string{
Bob: "Bob",
Jane: "Jane",
Ralph: "Ralph",
Nobody: "Nobody",
}

func (intValue PersonID) Name() string {
return idMap[intValue]
}

func Lookup(name string) PersonID {
return nameMap[name]
}

func (intValue PersonID) UnmarshalJSON(data []byte) error {
// The following line is not correct
intValue = Lookup(string(data))
return nil
}

type MyType struct {
Person PersonID `json: "person"`
Count int `json: "count"`
Greeting string `json: "greeting"`
}

func main() {
var m MyType
if err := json.Unmarshal([]byte(`{"person": "Ralph", "count": 4, "greeting": "Hello"}`), &m); err != nil {
fmt.Println(err)
} else {
for i := 0; i < m.Count; i++ {
fmt.Println(m.Greeting, m.Person.Name())
}
}
}

最佳答案

对解码方法使用指针接收器。如果使用值接收器,则在方法返回时对接收器所做的更改将丢失。

unmarshal 方法的参数是 JSON 文本。解码 JSON 文本以获得删除所有 JSON 引号的纯字符串。

func (intValue *PersonID) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
*intValue = Lookup(s)
return nil
}

JSON 标签与示例 JSON 不匹配。我更改了 JSON 以匹配标签,但您可以通过其他方式进行更改。

if err := json.Unmarshal([]byte(`{"person": "Ralph", "count": 4, "greeting": "Hello"}`), &m); err != nil {

playground example

关于json - 如何为从 Go 中的标量派生的类型实现 UnmarshalJSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34618940/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com