Golang:Protobuff生成的Struct无法解码json的子属性。

I have one struct which is getting used with protobuff serialiser and works well.

This struct is generated by protobuff hence it has so many methods like Unmarshal etc.

type Flight struct {
    FlightNo string  `json:"flightno, omitempty"`
    Carrier string   `json:"carrier, omitempty"`
}
func (m *Flight) Unmarshal(data []byte) error {
    l := len(data)
    iNdEx := 0
    for iNdEx < l {
        preIndex := iNdEx
        var wire uint64
        for shift := uint(0); ; shift += 7 {
            if shift >= 64 {
                return ErrIntOverflowFlight
            }
            if iNdEx >= l {
                return io.ErrUnexpectedEOF
            }
            b := data[iNdEx]
            iNdEx++
            wire |= (uint64(b) & 0x7F) << shift
            if b < 0x80 {
                break
            }
        }
    }
 // some more code
}

Then I want to add additional field to this flight info,

type FlightMeta struct {
    Source string `json:"source, omitempty"`
    Destination string `json:"destination, omitempty"`
}

Then i have combined struct of these two,

type CombinedFlight struct {
    Flight
    FlightMeta

}

type ResponseFlight struct {
    OnwardFlights  []CombinedFlight  `json:"onwardflights, omitempty"`
    ReturnFlights  []CombinedFlight  `json:"returnflights, omitempty"`
    Error string  `json:"error, omitempty"`
}

So when i read some data like,

str "= `{"onwardflights": [{"flightno": "537", "carrier": "AI", "source": "BOM", "destination": "DEL"}], "error": "false"}`
respFlight = new(ResponseFlight)

err = json.Unmarshal([]byte(str), &respFlight)

fmt.Println("flightno:", respFlight.OnwardFlights[0].FlightNo, "flight source", respFlight.OnwardFlights[0].Source)

#prints "flightno:537 flight source:

It doesn't print value for second struct, as per methis is not unmarshling properly.

But when i set the attribute manually and marshal(encode it to json) this is working fine. Any leads.?

Try to do this

        type CombinedFlight1 struct {
            Flight
            FlightMeta

        }


        type CombinedFlight2 struct {
            Flight
            FlightMeta

        }

        type ResponseFlight struct {
           OnwardFlights  []CombinedFlight1  `json:"onwardflights, omitempty"`
           ReturnFlights  []CombinedFlight2  `json:"returnflights, omitempty"`
           Error string  `json:"error, omitempty"`
        }

It will work fine and if you want to marshal, you have to create two different structure. For more understanding see this post

Visit Initialize nested struct definition in Golang if it have same objects