是否有可能消失 gin-gonic 中绑定 json 的范围?

Is it possible that disappearing a scope in gin-gonic binded json?

我正在用 gin-gonic 写一个 api 服务器。

我遇到了与编组相关的麻烦 json。

例如,我有如下结构。

type Foo struct {
    Value     float32 `json:"value"`
    Injection interface{}
}

然后我在 运行 时间内写下了一些字段并发送了响应。

r.GET("/ping", func(c *gin.Context) {

    var foo = &Foo{
        Value: 19.8,
        Injection: map[string]interface{}{
            "unit": "C",
            "constraints": map[string]interface{}{
                "min": 18,
                "max": 30,
            },
        },
    }

    c.JSON(200, foo)
})

因此,我可以看到这个 json 响应。

{
    "value": 19.8,
    "Injection": {
        "constraints": {
            "max": 30,
            "min": 18
        },
        "unit": "C"
    }
}

但是如果我想要下面的赞,我该怎么办?

{
    "value": 19.8,
    "constraints": {
        "max": 30,
        "min": 18
    },
    "unit": "C"
}

我尝试在 运行 时间内分配所有字段,第一次工作正常,但在添加许多字段后我遇到了地狱门。

所以我可以说这是 React 中的类似问题 <Fragment> 标签。

ps。抱歉,我不确定标题是否符合我的意思。

您可以直接使用地图而不是Foo

r.GET("/ping", func(c *gin.Context) {
    var data = map[string]interface{}{
        "value": 19.8,
        "unit":  "C",
        "constraints": map[string]interface{}{
            "min": 18,
            "max": 30,
        },
    }

    c.JSON(200, data)
})

如果您需要更通用的东西,您可以 Foo 实现 json.Marshaler 接口并让实现分别编组两个值,然后仅 "merge" 手动结果。

type Foo struct {
    Value     float32     `json:"value"`
    Injection interface{} `json:"-"`
}

func (f *Foo) MarshalJSON() ([]byte, error) {
    type tmp Foo
    out1, err := json.Marshal((*tmp)(f))
    if err != nil {
        return nil, err
    }
    out2, err := json.Marshal(f.Injection)
    if err != nil {
        return nil, err
    }

    out1[len(out1)-1] = ','           // replace the '}' at the end with ','
    out2 = out2[1:]                   // drop the leading '{'
    return append(out1, out2...), nil // merge
}

请注意,上面假设 Injection 持有一个值,如果该值是标量,则该值将被编组为 json 对象 ,或者切片类型,您需要以不同方式处理这些情况。

https://play.golang.com/p/kYIu6HnqVIp