【发布时间】:2020-01-23 06:53:57
【问题描述】:
我收到了一个物品:
{
"operation": "ACC00000001",
"prm": "23597250350000",
"conso_prod": "Conso",
"index_name": "BASE",
"index_value": "123456",
"timestamp": "2019-08-20T22:00:00Z"
}
我使用的对象在一个公共库中,因此它被多个服务共享:
common.Measure:
type Measure struct {
Timestamp time.Time
Delta float64
Redistributed float64
IsProd bool
IndexValue uint32
IndexName string
Source string
}
和仪表:
type Meter struct {
ID string
Operation string
Unit string
Timestep time.Duration
Measures []Measure
}
但由于标签不匹配,我必须创建另一个对象 MeasureFromJSON,它是基于我收到的 json 创建的。
type MeasureFromJSON struct {
Operation string `json:"operation" binding:"required"`
Prm string `json:"prm"`
Conso_prod string `json:"conso_prod"`
Index_name string `json:"index_name"`
Index_value string `json:"index_value"`
Timestamp string `json:"timestamp"`
}
问题是我不喜欢为同一个实体使用 2 个模型,因为我在公共对象中没有 JSON 标签。有没有办法使用常用模型(meter.Measure)?
【问题讨论】:
-
你试过
IndexName string `json:"index_name"`吗?或者您所说的“标签不匹配”到底是什么意思? -
为什么不在
common中的Measure中添加json标签?那么问题就解决了,还是我错过了什么? -
同一个实体怎么会返回2个不同的模型?
-
@icza 但是,我将无法对相同的对象进行不同的解析,对吗?
-
@JuliatzindelToro 我不明白你所说的不同解析是什么意思,你能举出具体的例子吗?