简体   繁体   中英

mgo error when unmarshal map[string]interface{}

I want to store an arbitrary json object in a struct:

type C struct {
  Name string `json:"name" bson:"name"`
  Config map[string]interface{} `json:"config" bson:"config"`
}

This works fine when I store any deeply nested json object, but when I go retrieve it and mgo tries to Unmarshal it, I get

Unmarshal can't deal with struct values. Use a pointer.

I'm not sure what's supposed to be a pointer. If I change it to

Config *map[string]interface{}

the same error occurs.

The error occurs here: https://github.com/MG-RAST/golib/blob/master/mgo/bson/bson.go#L493

I don't know what it's reflecting on though.

So when you are unmarshaling the input argument takes a pointer to the struct, and you need to define a type in order to use a pointer to a struct.

type myMap map[string]interface{}

Then you can make a pointer to that type notice the ampersand to indicate pointer to your struct for type myMap, with json you could do something like so:

json := []Byte{`{"name": "value"}`}
c := &myMap{"value": "name"}
json.Unmarshal(c, json)

So you need *myMap to the struct not a pointer to the type. In order to explain the specific solution to this problem you need to add the context of how mongodb is unmarshaling your json.

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