TPPZ
TPPZ

Reputation: 4891

Marshal to JSON struct extended another struct with the same field label

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\n", fooJsonStr)
    fmt.Printf("Bar: %s\n", barJsonStr)
}

Gives this output:

Foo: {"id":123,"stuff":"abc"} 
Bar: {"id":456,"stuff":"abc","other_stuff":"xyz"}

Upvotes: 1

Views: 908

Answers (1)

Volker
Volker

Reputation: 42413

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.

Upvotes: 1

Related Questions