简体   繁体   English

自定义 JSON 结构解组

[英]Custom JSON struct Unmarshal

I'm using an API that returns the result as the name of the object and I am trying to unmarshal just the fields of the struct.我使用的 API 将结果作为对象的名称返回,并且我试图仅对结构的字段进行解组。 Here is an example of the JSON:以下是 JSON 的示例:

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

You can see it is using "AAPL" as the name of the struct and I'm not sure how to unmarshal it.你可以看到它使用“AAPL”作为结构的名称,我不知道如何解组它。 I'm looking to unmarshal into this struct:我希望解组到这个结构中:

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

I assume I need to write a custom unmarshal func我假设我需要编写一个自定义解组函数

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

I'm not sure of the contents.我不确定内容。 Any assistance is appreciated!任何帮助表示赞赏!

I think you are looking for json:"-".我认为您正在寻找 json:"-"。

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

As a special case, if the field tag is "-", the field is always omitted.作为一种特殊情况,如果字段标记为“-”,则始终省略该字段。 Note that a field with name "-" can still be generated using the tag "-,".请注意,名称为“-”的字段仍然可以使用标签“-,”生成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM