gpt4 book ai didi

json - 从 relfect.Value 编码 JSON

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

在 encoding/json 下,它使用 relfect 编码结构。

但是我如何编码已经是一种 reflect.Value 的东西

查看下面的代码:

type Person struct {
Name string `json:"name"`
Pwd string `json:"pwd"`
}

func main() {
factory := map[string]reflect.Type{
"Person":reflect.TypeOf(Person{}),
}

s := reflect.New(factory["Person"]).Elem()
s.Field(0).SetString("Max")
s.Field(1).SetString("Password")
j, err := json.Marshal(s)
if err != nil {
fmt.Println("error")
}
fmt.Println(j)
}

输出是这样的:

[123 34 102 108 97 103 34 58 52 48 54 125]

这是什么?执行此操作的正确方法是什么,我的意思是从 reflect.Value 类型获取正确的 json 字符串?

最佳答案

使用 (reflect.Value).Interface() 获取可以进行 JSON 编码的 interface{} 类型的值:

j, err := json.Marshal(s.Interface())

关于你的问题:

[123 34 102 108 97 103 34 58 52 48 54 125]

是字符串 {"flag":406},打印为 byte slice 段(这是 json.Marshal 返回的内容)。

关于json - 从 relfect.Value 编码 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25349694/

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