自定义 JSON 结构 Unmarshal



>我正在使用一个将结果作为对象名称返回的 API,并且我正在尝试仅取消封送结构的字段。下面是 JSON 的示例:

{
"AAPL": {
"symbol": "AAPL",
"description": "Apple Inc. - Common Stock",
"lastPrice": 284.45,
"openPrice": 284.69,
"highPrice": 284.89,
"lowPrice": 282.9197,
}
}

您可以看到它使用"AAPL"作为结构的名称,我不确定如何取消编组它。我希望解组到这个结构中:

type Quote struct {
Symbol                    string  `json:"symbol"`
Description               string  `json:"description"`
LastPrice                 float64 `json:"lastPrice"`
OpenPrice                 int     `json:"openPrice"`
HighPrice                 int     `json:"highPrice"`
LowPrice                  int     `json:"lowPrice"`
}

我假设我需要编写一个自定义的解组函数

func (q *Quote) UnmarshalJSON(b []byte) error {
...
}

我不确定内容。任何帮助不胜感激!

我想你正在寻找json:"-"。

https://golang.org/pkg/encoding/json/#Marshal

作为特殊情况,如果字段标记为"-",则始终省略该字段。请注意,名称为"-"的字段仍可以使用标记"-","生成。

最新更新