Flattening marshalled JSON structs with anonymous members in Go

前端 未结 7 1941
感情败类
感情败类 2021-01-02 10:20

Given the following code: (reproduced here at play.golang.org.)

package main

import (
    "encoding/json"
    "fmt"
)

type User struct {         


        
相关标签:
7条回答
  • 2021-01-02 11:21

    I needed to do something similar and tried your technical of the embedded interface and (no surprise) had the same issue.

    I didn't want to have to alter all the possible structs that needed additional fields, but ultimately I compromised with this solution:

    http://play.golang.org/p/asLFPx76jw

    package main

    import (
        "encoding/json"
        "fmt"
    )
    
    type HateoasFields struct {
        Links []interface{} `json:"_links,omitempty"`
    }
    
    type User struct {
        Id   int    `json:"id"`
        Name string `json:"name"`
        HateoasFields
    }
    
    type Session struct {
        Id     int `json:"id"`
        UserId int `json:"userId"`
        HateoasFields
    }
    
    func main() {
        u := &User{Id: 123, Name: "James Dean"}
        s := &Session{Id: 456, UserId: 123}
    
        u.Links = []interface{}{fmt.Sprintf("http://user/%d", u.Id)}
        s.Links = []interface{}{fmt.Sprintf("http://session/%d", s.Id)}
    
        uBytes, _ := json.Marshal(u)
        sBytes, _ := json.Marshal(s)
    
        fmt.Println(string(uBytes))
        fmt.Println(string(sBytes))
    }
    

    Which outputs:

    {"id":123,"name":"James Dean","_links":["http://user/123"]}
    {"id":456,"userId":123,"_links":["http://session/456"]}
    

    Rather than embedding the original structs in a struct with the additional fields, I did the opposite.

    When looking at your original code, I don't think this solution is that awesome. How is this better than adding the Links property to the original struct? But for my app needs it was the best thing.

    0 讨论(0)
提交回复
热议问题