我正在工作中编写一个Golang API,该API在被调用时会从两个不同的MongoDB集合中获取数据,并将其附加到一个结构中,将其转换为JSON,然后进行字符串化处理并发送给API(Amazon SQS)
问题是,定义了从MongoDB接收的数据的结构,尽管某些字段定义正确,但某些字段有所不同
// IncentiveRule struct defines the structure of Incentive rule from Mongo
type IncentiveRule struct {
... Other vars
Rule Rule `bson:"rule" json:"rule"`
... Other vars
}
// Rule defines the struct for Rule Object inside an incentive rule
type Rule struct {
...
Rules interface{} `bson:"rules" json:"rules"`
RuleFilter RuleFilter `bson:"rule_filter" bson:"rule_filter"`
...
}
// RuleFilter ...
type RuleFilter struct {
Condition string `bson:"condition" json:"condition"`
Rules []interface{} `bson:"rules" json:"rules"`
}
虽然这有效,但在interface{}
结构中定义的Rule
是变化的,并且在获取为BSON并解码并重新编码为JSON时,而不是在JSON中编码为"fookey":"barvalue"
时,它被编码为"Key":"fookey","Value":"barvalue"
,如何避免这种行为并将其显示为"fookey":"barvalue"