在 Go 中使用匿名成员扁平化 JSON 结构
在 Go 中,匿名结构字段通常被封送,就好像它们的内部导出字段是外部结构中的字段一样。然而,当使用接口{}类型的匿名成员封送结构时,这可能会导致意外行为。
问题
考虑以下示例:
<code class="go">type User struct { Id int `json:"id"` Name string `json:"name"` } type Session struct { Id int `json:"id"` UserId int `json:"userId"` } type Anything interface{} type Hateoas struct { Anything Links map[string]string `json:"_links"` } func MarshalHateoas(subject interface{}) ([]byte, error) { h := &Hateoas{subject, make(map[string]string)} switch s := subject.(type) { case *User: h.Links["self"] = fmt.Sprintf("http://user/%d", s.Id) case *Session: h.Links["self"] = fmt.Sprintf("http://session/%d", s.Id) } return json.MarshalIndent(h, "", " ") } func main() { u := &User{123, "James Dean"} s := &Session{456, 123} json, err := MarshalHateoas(u) if err != nil { panic(err) } else { fmt.Println("User JSON:") fmt.Println(string(json)) } json, err = MarshalHateoas(s) if err != nil { panic(err) } else { fmt.Println("Session JSON:") fmt.Println(string(json)) } }</code>
运行时这段代码,生成的 JSON 与预期不符:
<code class="json">User JSON: { "Anything": { "id": 123, "name": "James Dean" }, "_links": { "self": "http://user/123" } } Session JSON: { "Anything": { "id": 456, "userId": 123 }, "_links": { "self": "http://session/456" } }</code>
如您所见,匿名成员 Anything 被视为 JSON 中的命名字段,这不是预期的行为。
解决方案
为了扁平化匿名成员并实现所需的 JSON 结构,我们可以使用 Reflect 包来循环结构体的字段并将它们映射到 map[string]interface{}。这使我们能够保留原始结构体的扁平结构,而无需引入新字段。
更新后的代码如下:
<code class="go">import ( "encoding/json" "fmt" "reflect" ) // ... (rest of the code remains the same) func MarshalHateoas(subject interface{}) ([]byte, error) { links := make(map[string]string) out := make(map[string]interface{}) subjectValue := reflect.Indirect(reflect.ValueOf(subject)) subjectType := subjectValue.Type() for i := 0; i <p>通过此修改,生成的 JSON 被正确展平: </p> <pre class="brush:php;toolbar:false"><code class="json">User JSON: { "id": 123, "name": "James Dean", "_links": { "self": "http://user/123" } } Session JSON: { "id": 456, "userId": 123, "_links": { "self": "http://session/456" } }</code>
以上是如何在 Go JSON 序列化中压平匿名接口字段?的详细内容。更多信息请关注PHP中文网其他相关文章!

文章讨论了使用“ For”,“循环类型”,“优化技术”以及避免常见错误的创建循环。主要重点是GO中的有效循环使用。[159个字符]

Golang使用各种数据类型,例如BOOL,INT,UINT,FLOAT,String和符文,用于不同的数据表示。讨论了INT和UINT之间的关键差异,以及使用字符串与符文的使用。

goisastrongchoiceforprojectsneedingsimplicity,绩效和引发性,butitmaylackinadvancedfeatures and ecosystemmaturity.1)

Go'sinitfunctionandJava'sstaticinitializersbothservetosetupenvironmentsbeforethemainfunction,buttheydifferinexecutionandcontrol.Go'sinitissimpleandautomatic,suitableforbasicsetupsbutcanleadtocomplexityifoverused.Java'sstaticinitializersoffermorecontr

thecommonusecasesfortheinitfunctionoare:1)加载configurationfilesbeforeThemainProgramStarts,2)初始化的globalvariables和3)runningpre-checkSorvalidationsbeforEtheprofforeTheProgrecce.TheInitFunctionIsautefunctionIsautomentycalomationalmatomatimationalycalmatemationalcalledbebeforethemainfuniinfuninfuntuntion

ChannelsarecrucialingoforenablingsafeandefficityCommunicationBetnewengoroutines.theyfacilitateSynChronizationAndManageGoroutIneLifeCycle,EssentialforConcurrentProgramming.ChannelSallSallSallSallSallowSallowsAllowsEnderDendingAndReceivingValues,ActassignalsignalsforsynChronization,and actassignalsynChronization and andsupppor

在Go中,可以通过errors.Wrap和errors.Unwrap方法来包装错误并添加上下文。1)使用errors包的新功能,可以在错误传播过程中添加上下文信息。2)通过fmt.Errorf和%w包装错误,帮助定位问题。3)自定义错误类型可以创建更具语义化的错误,增强错误处理的表达能力。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

Atom编辑器mac版下载
最流行的的开源编辑器