如何在 go 中构建抽象 json 解组器

我有多个 API,它们在高级响应上遵循类似的结构。它总是以这种形式返回答案:


{"data": {"feed":[{...}]}, "success": true}

然而,Feed 中的结构会有所不同,具体取决于具体的 API。


我现在想构建一个抽象函数来处理各种 API。我有以下对象:


type SourceDTO struct { // top level object

    Success bool       `json:"success"`

    Data    Feed       `json:"data"`

}


type Feed struct {

    FeedData []<???> `json:"Feed"`

}

(真实的物体更复杂,但这表明了想法)


如果有一些通用代码和一些基于高级数据(例如成功)的逻辑,那么 go 为不同的 API 解析这个问题的好方法是什么?


编辑: 我正在扩展这个,以更多地解释我关于我正在寻找的“模式”的问题的扩展。


我想创建这个解析 API 组的包。然后必须将 DTO 对象转移到其他一些对象中。这些“最终”对象在不同的包(实体包)中定义,然后必须被持久化。

我现在想知道如何将所有这些整合在一起:“最终”实体对象、从 DTO 到实体的转换函数、不同 API 的解析及其常见和不同的结果组件。

转换函数属于哪里(包方面)?


EDIT2:深入研究问题后将 FeedData 指定为切片(请参阅评论)


json去


墨色风雨
浏览 101回答 2
2回答

MYYA

您可以将SourceDTO结构嵌入到另一个结构中,如下所示:type SourceDTO struct { // top level object&nbsp; &nbsp; Success bool&nbsp; &nbsp; &nbsp; &nbsp;`json:"success"`}type FeedResponse struct {&nbsp; &nbsp; FeedData YourCustomFeedStruct `json:"feed"`&nbsp; &nbsp; // Embedded Struct&nbsp; &nbsp; SourceDTO}Success现在您可以从 FeedResponse 结构访问bool。SourceDTO此外,可以从 FeedResponse 访问该结构上定义的任何方法。

慕工程0101907

为了在 json 解组中有一些抽象,它可以用于interface{}许多用例。package mainimport (&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "fmt")type UniversalDTO struct {&nbsp; &nbsp; Success bool&nbsp; &nbsp; &nbsp; &nbsp; `json:"success"`&nbsp; &nbsp; Data&nbsp; &nbsp; interface{} `json:"data"`}type ConcreteData struct {&nbsp; &nbsp; Source string `json:"source"`&nbsp; &nbsp; Site&nbsp; &nbsp;string `json:"site"`}func main() {&nbsp; &nbsp; jsondata := []byte(`{"sucess":"true","data":[{"source":"foo","site":"bar"}]}`)&nbsp; &nbsp; data := make([]ConcreteData, 0, 10)&nbsp; &nbsp; dtoToSend := UniversalDTO{Data: &data}&nbsp; &nbsp; describe(dtoToSend)&nbsp; &nbsp; describe(dtoToSend.Data)&nbsp; &nbsp; json.Unmarshal(jsondata, &dtoToSend)&nbsp; &nbsp; describe(dtoToSend)&nbsp; &nbsp; describe(dtoToSend.Data)}func describe(i interface{}) {&nbsp; &nbsp; fmt.Printf("(%v, %T)\n", i, i)}在这里测试: https: //play.golang.org/p/SSSp_zptMVNjson.Unmarshal需要一个将 json 放入其中的对象。因此,首先我们总是需要一个对象。根据目标对象的具体实例,可以使用具体的结构对象(当然必须单独创建)覆盖interface{} 。这里一个重要的学习是,go接口也可以用 slice 覆盖。通过这种方式,也可以将数组解组为 go 对象。但是,结构体的切片必须定义为指向该类型的指针的切片。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go