简体   繁体   中英

json ignore tag (“-”) not working on embedded sub structure

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

之前 后

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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