使用Go 展平JSON 中的嵌入匿名結構
在提供的程式碼中,MarshalHateoas 函數以以下方式展平結構體的JSON 表示:嵌入匿名結構作為Hateoas 結構的成員。但是,匿名成員的字段被視為單獨的命名字段,從而導致不良的 JSON 輸出。
要解決此問題,可以利用 Reflect 套件循環嵌入結構的欄位並手動將它們映射到扁平化表示。這是MarshalHateoas 的修改版本:
<code class="go">import ( "encoding/json" "fmt" "reflect" ) // ... func MarshalHateoas(subject interface{}) ([]byte, error) { links := make(map[string]string) // Retrieve the unexported fields of the subject struct subjectValue := reflect.Indirect(reflect.ValueOf(subject)) subjectType := subjectValue.Type() // Iterate over the fields of the embedded anonymous struct for i := 0; i <p>透過動態建構的映射取代匿名成員,MarshalHateoas 函數現在可以正確地展平JSON 輸出:</p> <pre class="brush:php;toolbar:false"><code class="json">{ "id": 123, "name": "James Dean", "_links": { "self": "http://user/123" } }</code>
此解決方案允許從具有嵌入匿名成員的結構建立扁平化JSON 表示,無需引入新欄位或依賴特定於平台或依賴庫的技巧。
以上是如何使用 Go 扁平化 JSON 中的嵌入式匿名結構?的詳細內容。更多資訊請關注PHP中文網其他相關文章!