gpt4 book ai didi

go - 将 JSON 解码为结构

转载 作者:IT王子 更新时间:2023-10-29 02:02:37 31 4
gpt4 key购买 nike

当在 JSON 字符串中给出结构类型时,如何将 JSON 字符串解码为结构。这是我的代码:

package main

import (
"fmt"
"encoding/json"
)

type ServiceResult struct {
Type string `json:"type"`
Content interface{} `json:"content"`
}

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

func main() {

nikola := ServiceResult{}
nikola.Type = "Person"
nikola.Content = Person{"Nikola"}

js, _ := json.Marshal(nikola)
fmt.Println("Marshalled object: " + string(js))
}

And now I want to create from this JSON string a new person but the type has to be read out of the JSON string.

{"type":"Person","content":{"name":"Nikola"}}

最佳答案

首先,对于你的类型

type ServiceResult struct {
Type string `json:"type"`
Content interface{} `json:"content"`
}

您需要通过定义来实现“自定义 JSON 解码器”一个方法:

func (sr *ServiceResult) UnmarshalJSON(b []byte) error

让你的类型满足 encoding/json.Unmarshaler 接口(interface) —这将使 JSON 解码器在解码时调用该方法该类型的值。

在该方法中,您可以使用辅助类型

type typedObject struct {
Type string `json:"type"`
Content json.RawMessage `json:"content"`
}

首先解码 b slice 。

如果解码完成而没有产生错误,您的值typedObject 类型的将具有描述类型的字符串在其 Type 字符串和包含的原始(未解析的)JSON 字符串中在其 Content 字段的“content”字段中。

然后你做一个switch(或 map 查找或其他)来执行选择实际的 Go 类型来解码 Content 中的任何数据进入其中,例如:

var value interface{}
switch sr.Type {
case "person":
value = new(Person)
case "car":
value = new(Car)
}
err = json.Unmarshal(sr.Content, value)

...其中 PersonCar 是具体的结构类型适当武装以供 encoding/json 使用。

请阅读thisthis以充分理解这些概念。

关于go - 将 JSON 解码为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47051538/

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