- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
新手golang程序员在这里。我正在重写一个 Java 应用程序。 Java 应用程序使用利用 Jackson 的 Polymorphic Typing 的对象模型。处理编码/解码到/从 JSON 的功能。假设我无法更改 JSON 对象的形状。
鉴于 Go 为多态提供的产品是 interface{},因此很难提出一个“对象模型”来提供与多态相关的相同使用模式。
我第一次尝试解决看起来像这样:
type Thing struct {
ID string `json:"id"`
Type string `json:"@type"`
}
type SpecificThing struct {
Thing
SpecificField string `json:"specificField"`
}
type AnotherSpecificThing struct {
Thing
AnotherSpecificField string `json:"anotherSpecificField"`
}
type Thing struct {
ID string `json:"id"`
Type string `json:"@type"`
Payload interface{} `json:"-"`
}
type SpecificThing struct {
SpecificField string `json:"specificField"`
}
type AnotherSpecificThing struct {
AnotherSpecificField string `json:"anotherSpecificField"`
}
type superThing struct {
ID string `json:"id"`
Type string `json:"@type"`
*SpecificThing
*AnotherSpecificThing
}
func (t *Thing) UnmarshalJSON(b []byte) error {
//error checking omitted for brevity
var st superThing
_ = json.Unmarshal(b, &st)
t.ID = st.ID
t.Type = st.Type
switch t.Type {
case "specificThing":
t.Payload = st.SpecificThing
case "anotherSpecificThing":
t.Payload = st.AnotherSpecificThing
}
return nil
}
func TestUnmarshal(t *testing.T) {
data := []byte(`
{
"id":"some id",
"@type":"specificThing",
"specificField": "some specific field value"
}
`)
var th Thing
_ = json.Unmarshal(data, &th)
}
最佳答案
我认为使 Thing 成为接口(interface)并实现 UnmarshalJSON 这几乎可以满足您的需求(如果用户需要接口(interface)未提供的功能,那么用户仍然必须使用类型断言/切换,但这几乎是不可避免的)。这将类似于以下内容:
package main
import (
"encoding/json"
"fmt"
)
func main() {
data := []byte(`
{
"id":"some id",
"@type":"specificThing",
"specificField": "some specific field value"
}
`)
var th ThingHolder
err := json.Unmarshal(data, &th)
if err != nil {
panic(err)
}
mySpecThing := th.T.(*SpecificThing )
fmt.Printf("%v", mySpecThing)
}
type Thing interface {
ID() string
}
type ThingHolder struct {
T Thing
}
type SpecificThing struct {
Id string `json:"id"`
Type string `json:"@type"`
SpecificField string `json:"specificField"`
}
func (s *SpecificThing) ID() string {
return s.Id
}
func (t *ThingHolder) UnmarshalJSON(b []byte) error {
var objMap map[string]*json.RawMessage
err := json.Unmarshal(b, &objMap)
if err != nil {
return err
}
// Now lets see what 'things' the JSON contains
// by looking at JSON keys
jsonType, ok := objMap["@type"]
if !ok {
return fmt.Errorf("No Type")
}
var goType string
err = json.Unmarshal(*jsonType, &goType)
if err != nil {
return fmt.Errorf("error getting type: %s", err)
}
switch goType {
case "specificThing":
var st SpecificThing
err = json.Unmarshal(b, &st)
if err != nil {
return err
}
t.T = &st
default:
return fmt.Errorf("Unknown type %s", goType )
}
return nil
}
关于json - 从 Java 到 Golang : Unmarshaling Polymorphic JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59080215/
json: 无法将数组解码为 Go 类型的值 配置 json: { "monitor_servers_info":[ { "server
我有一个看起来像这样的 JSON blob { "metadata":{ "id":"2377f625-619b-4e20-90af-9a6cbfb80040",
我正在向第 3 方 API 发出 JSON 请求。如果我的身份验证 token 已过期,我会收到 {"error": "message"} .如果一切顺利,我会收到有效的回复。 现在,我调用json.
这个问题在这里已经有了答案: json.Marshal(struct) returns "{}" (3 个答案) 关闭 6 年前。 我在解码从 .json 文件中读取的 json 数据时遇到问题 t
我正在尝试从文件中读取并将其加载到结构 slice 中。如 block 注释中所示,我读入的行已正确加载。 我遇到的问题是 class 变量总是返回空值。我做错了什么? func loadClasse
我很难理解为什么下面使用 unmarshal 方法的代码不起作用,但我用 NewDecoder 编写的代码几乎相同,而且运行良好。 package conf import ( "os"
我目前遇到以下问题: 我通过 websocket 得到一个 []byte/string 看起来像 eventname {"JSON": "data", "In": "different formats
我正在从本地主机读取一个 json 文档并尝试将其转换为 Test 类型: type Test struct { one string two string three str
这个问题在这里已经有了答案: My structures are not marshalling into json [duplicate] (3 个答案) 关闭 6 年前。 我有以下代码: pac
我正在开发一个 RSS 阅读器应用程序,遇到了纽约时报 RSS 提要的问题。我已将问题缩小到以下 XML(省略了不必要的字段): https://www.nytimes.com/2017/09/
我有一个如下所示的 JSON 对象: {"API version":"1.2.3"} 我想使用 json.Unmarshal() 将它转换为一个对象去功能。根据this blog post : How
我有一个像这样的 JSON blob { "metadata":{ "id":"2377f625-619b-4e20-90af-9a6cbfb80040", "
我已经被这个问题困扰了几个星期了。我有一个从 Autonomy IDOL 搜索中收到的 XML 文档,可以将其成功解码为一组 Java 对象。但是,如果有国际字符,例如中文、日文、俄文/西里尔文,它们
我有一个图像数据结构 type ImageData struct { Name string Data []byte } 数据字段是转换为字节的图像。 我有jsonImages和[{"
这不是Stop json.Marshal() from stripping trailing zero from floating point number的副本,因为我希望和编码(marshal)(
在此链接:JAXB Unmarshalling XML string - Looping through all tags有人提出了一个很好的解决方案。我试图从中受益,但我无法让它在我的情况下发挥作用
我正在尝试解码一个没有注释的编码对象。 这是我的对象类。 class Student { private String name; private int age; publi
我在各种堆栈溢出帖子和博客条目中看到了以下语法: JAXBElement sc = unmarshaller.unmarshal(is, SomeClass.class); 那么当我尝试使用此语法时,
我必须在 Java 对象中解析 XML,并且 XML 包含一个未包装的对象列表,如下所示: Main Property A Main Property B
刚开始使用 Go,我对我正在学习的教程有一点疑问。我读到 Unmarshall 是某种 JSON 编码,我的疑问是:err = json.Unmarshal(body, &p) 为什么我们要将编码后的
我是一名优秀的程序员,十分优秀!