Flattening marshalled JSON structs with anonymous members in Go

前端 未结 7 1939
感情败类
感情败类 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 10:58

    One approach which I've worked through involves the use of methods on types. Please see http://play.golang.org/p/bPWB4ryDQn for more details.

    Basically, you work the problem from the opposite angle -- instead of "encapsulating" a base type into a Hateoas type, you instead incorporate the required map in each of your base types. Then, implement a method on each of those base types, which is responsible for updating the Links field accordingly.

    This produces the intended result, and with only marginal source code boiler-plate.

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

    I believe any other way than this, particularly if you persue the embed-and-extend approach, will require implementing a custom marshaler (http://golang.org/pkg/encoding/json/#Marshaler) and will likely require the use of the reflect package as well, especially since anything is of type interface{}.

提交回复
热议问题