dscizpq790832708 2018-05-22 12:49
浏览 78
已采纳

元帅到JSON结构扩展了另一个具有相同字段标签的结构

  • I have 2 struct containing a field with the same label (id) and the same JSON annotation (`json:"id"`).
  • One struct (Bar) includes the fields labels and their values from the other struct (Foo).

I would like to JSON marshal the wrapper struct Bar with both the id fields, but the inner one with a different JSON annotation (e.g. `json:"foo_id"`). I can not find a way to do it, but it looks like something that should be doable?

Having a quick look here https://golang.org/pkg/encoding/json/ I can not find the solution.

Is it possible at all? Is there any work around? I am trying to avoid all the boiler plate of get/set to copy/paste values between structs, I hope this is doable somehow.

package main

import (
    "encoding/json"
    "fmt"
)

type Foo struct {
    ID int `json:"id"`
    Stuff string `json:"stuff"`
}

type Bar struct {
    ID int `json:"id"`
    Foo
    // the following does not work, 
    // I've tried a few variations with no luck so far
    // Foo.ID int `json:"foo_id"`
    OtherStuff string `json:"other_stuff"`
}

func main() {
    foo := Foo{ID: 123, Stuff: "abc" }
    bar := Bar{ID: 456, OtherStuff: "xyz", Foo: foo }

    fooJsonStr, _ := json.Marshal(foo)
    barJsonStr, _ := json.Marshal(bar)

    fmt.Printf("Foo: %s
", fooJsonStr)
    fmt.Printf("Bar: %s
", barJsonStr)
}

Gives this output:

Foo: {"id":123,"stuff":"abc"} 
Bar: {"id":456,"stuff":"abc","other_stuff":"xyz"}
  • 写回答

1条回答 默认 最新

  • dp6319 2018-05-22 13:21
    关注

    One struct (Bar) inherit from the other struct (Foo).

    Obviously not as there is no inheritance in Go.

    If yout want Foo's ID to be named foo_id:

    type Foo struct {
        ID int `json:"foo_id"`
        Stuff string `json:"stuff"`
    }
    

    Dead simple.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图