The first bson.ObjectID that you show isn't actually what is stored in the 
object, but rather it is hex value of the object ID that is acquired by 
calling 

id.Hex()

It looks like that isn't what gets printed out when marshaling your map, 
and instead the IDs are printed out as whatever the raw value stored in a 
bson.ObjectID are.

You could update your code to instead store a string for the map where the 
key is `id.Hex()` instead of just the id. Eg:

type Stats struct {
A bson.ObjectId         `json:"a,omitempty" bson:"a,omitempty"`
B map[string]CustomType `json:"b,omitempty" bson:"b,omitempty"`
}

type CustomType struct {
Name string
}

func main() {
id := bson.NewObjectId()
stats := Stats{
A: id,
B: map[string]CustomType{
id.Hex(): CustomType{"jon"},
},
}
bytes, err := json.Marshal(stats)
if err != nil {
panic(err)
}
fmt.Println(string(bytes))
}


If you really want this data to be a `map[bson.ObjectID]CustomType` you 
could likely do this with a custom type like so

type BsonMap map[bson.ObjectID]CustomType

And then implementing the https://golang.org/pkg/encoding/json/#Unmarshaler 
and https://golang.org/pkg/encoding/json/#Marshaler interfaces. 

Hope that helps!
Jon


On Wednesday, December 21, 2016 at 1:40:33 PM UTC-5, Vincent Jouglard wrote:
>
> Hi,
>
> I am sending a map of elements indexed by a bson.ObjecId(), coming from 
> the bdd.
>
>
> type Stats struct {
>  A bson.ObjectId                 `json:"a,omitempty" bson:"a,omitempty"`
>  B map[bson.ObjectId]CustomType   `json:"b,omitempty" bson:"b,omitempty"`
> }
>
>
> // t is of type Stats 
> if err = c.WriteJSON(t); err != nil { // c is of type *Conn from mux 
> websocket, and this is where magic happens
>  fmt.Println("write:", err) // Nothing is triggered here
>  break
> }
>
>
> The result is not as expected :
>
>
>    "57ffdff9687a95381c5831d3" // this is A
>    B:{,…} 
>    W6�0�������}: // this is the index of the first element of B
>    W6�3�������
>    
>       
> The bson.ObjectId object A is healthy as expected, while the indexes of 
> the elements of B are quite unreadable.
> I have tried WriteJson and (Marshal + WriteMessage) - both WriteJson and 
> WriteMessage are wrappers of the native methods, from gorilla/mux -
>
> Do you know of anything special marshaling map[bson.ObjectId] ?
>
> Thanks for your help,
>    
>    
>    
>    1. 
>       
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to