我有一个我收到的对象:
{
"operation": "ACC00000001",
"prm": "23597250350000",
"conso_prod": "Conso",
"index_name": "BASE",
"index_value": "123456",
"timestamp": "2019-08-20T22:00:00Z"
}
我使用的对象在一个公共(public)库中,因此它被多个服务共享:
常用度量:
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 个模型,只是因为我在公共(public)对象中没有 JSON 标签。有没有办法使用常见的模型(meter.Measure
)?
最佳答案
Thing is I don't like to use 2 models for the same entity, just because I have no JSON labels in common object
首先我有一个疑问,同一个实体怎么会返回两组不同的数据,大部分字段都不一样呢?
如果那些不同的字段仍然来自单个实体,那么您可能可以组合这些字段并将其存储到单个 common.Measure
中。
type Measure struct {
Timestamp time.Time `json:"timestamp"`
Delta float64
Redistributed float64
IsProd bool
IndexValue string `json:"index_value"`
IndexName string `json:"index_name"`
Source string
ConsoProd string `json:"conso_prod"`
Prm string `json:"prm"`
Operation string `json:"operation"`
}
关于json - 如果我想在 2 个不同的 JSON 中解析对象,如何避免重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58058437/