dongyou9721 2019-03-08 20:14
浏览 72

json忽略标签(“-”)在嵌入式子结构上不起作用

I have been reading a lot of related questions but could not find anything that actually fit my problem. I am trying to unmarshall a complex object.

type DC struct {

    //other fields
    ReplenishmentData map[string]ProductReplenishment `bson:"-"`
    //other fields
}

type ProductReplenishment struct {
    //Other fields
    SafetyStockInDay int `json:"SafetyStockInDay" bson:"SafetyStockInDay"`
    AlreadyOrderedQuantityForReplenishment *map[float64]*UnitQuantity `json:"-" bson:"-"`
    //Other fields
}

Lets say I decode the following json:

{
  "ReplenishmentData": {
    "000822-099": {
      "SafetyStockInDay": 7
    },
    "001030-001": {
      "SafetyStockInDay": 7
    }
  }
}

Into a structure instance hierachy in which the AlreadyOrderedQuantityForReplenishment is not empty, after decoding this field will be set to and empty map, overriding the initial value.

Why is the decoder not ignore the field all together as specified in the docs? Am I missing something?

Thanks a lot for any help,

Adding screenshot of inspector before (first) / after (second) if that can help

before after

  • 写回答

1条回答 默认 最新

  • dongxiaolin2801 2019-03-08 20:37
    关注

    Your problem is not related to embedded structs - the same issue would occur with a regular struct.

    Encoders will skip encoding struct fields marked with the tag qualifier "-". Decoders when initializing a struct, will use the zero-value for any field that is not initialized via the decoding process. So your map will he initialized to a nil (empty) map.

    If you want to preserve settings you'd need to write your own (JSON or BSON) marshaler (doable - but not trivial). Or it may be just as simpler to just restore any zero-values after the decoding process.

    评论

报告相同问题?

悬赏问题

  • ¥15 Matlab问题解答有两个问题
  • ¥50 Oracle Kubernetes服务器集群主节点无法访问,工作节点可以访问
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。
  • ¥15 stm32的can接口不能收发数据
  • ¥15 目标检测算法移植到arm开发板
  • ¥15 利用JD51设计温度报警系统
  • ¥15 快手联盟怎么快速的跑出建立模型