gpt4 book ai didi

json - Golang : Protobuff generated Struct is not decoding child attribute for json. 解码

转载 作者:数据小太阳 更新时间:2023-10-29 03:26:33 26 4
gpt4 key购买 nike

我有一个结构体正在与 protobuff 序列化器一起使用并且运行良好。

这个结构是由 protobuff 生成的,因此它有很多方法,比如 Unmarshal 等。

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
}

然后我想为这个航类信息添加额外的字段,

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

然后我结合了这两个结构,

type CombinedFlight struct {
Flight
FlightMeta

}

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

所以当我读取一些数据时,比如,

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:

它不打印第二个结构的值,因为按照我的说法,这没有正确解码。

但是当我手动设置属性并编码(将其编码为 json)时,这工作正常。有线索吗?

最佳答案

尝试这样做

        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"`
}

它会很好地工作,如果你想编码,你必须创建两个不同的结构。如需更多了解,请参阅这篇文章

访问Initialize nested struct definition in Golang if it have same objects

关于json - Golang : Protobuff generated Struct is not decoding child attribute for json. 解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39851428/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com