Michael
Michael

Reputation: 7113

Unmarshal JSON object of strings, ints and arrays into a map

I like to unmarshal a JSON string using Decode():

var message Message
decoder := json.NewDecoder(s)
err = decoder.Decode(&message)

My data structure is

type Message map[string]interface{}

The test data is as follows:

{
  "names": [
    "HINDERNIS",
    "TROCKNET",
    "UMGEBENDEN"
  ], 
  "id":1189,
  "command":"checkNames"
}

It's working fine for numbers and strings, but with the string array I get following panic:

panic: interface conversion: interface is []interface {}, not []string

Upvotes: 1

Views: 245

Answers (1)

Adam Vincze
Adam Vincze

Reputation: 871

this is not possible by conversion because a slice of struct != slice of interface it implements!
either you can get the elements one by one and put them into a []string like this: http://play.golang.org/p/1yqScF9yVX

or better, use the capabilities of the json package to unpack the data in your model format : http://golang.org/pkg/encoding/json/#example_Unmarshal

Upvotes: 2

Related Questions