52

I get a string through a rabbitmq message system. Before sending,

I use json.Marshal, convert the outcome to string and send through rabbitmq.

The structs that I convert and send can be: (changed the names and the size of the structs but it should not matter)

type Somthing1 struct{
   Thing        string    `json:"thing"`
   OtherThing   int64     `json:"other_thing"`
}

or

type Somthing2 struct{
   Croc        int       `json:"croc"`
   Odile       bool      `json:"odile"`
}

The message goes through perfectly as a string and is printed on the other side (some server)

Up until now everything works. Now I'm trying to convert them back into their structs and assert the types.

first attempt is by:

func typeAssert(msg string) {

 var input interface{}

 json.Unmarshal([]byte(msg), &input)

 switch input.(type){
 case Somthing1:
    job := Somthing1{}
    job = input.(Somthing1)
    queueResults(job)

  case Somthing2:
    stats := Somthing2{}
    stats = input.(Somthing2)
    queueStatsRes(stats)
 default:
}

This does not work. When Printing the type of input after Unmarshaling it I get map[string]interface{} (?!?)

and even stranger than that, the map key is the string I got and the map value is empty.

I did some other attempts like:

 func typeAssert(msg string) {

  var input interface{}

  json.Unmarshal([]byte(msg), &input)

  switch v := input.(type){
  case Somthing1:
    v = input.(Somthing1)
    queueResults(v)

   case Somthing2:
    v = input.(Somthing2)
    queueStatsRes(v)
  default:
}

and also tried writing the switch like was explained in this answer: Golang: cannot type switch on non-interface value

switch v := interface{}(input).(type)

still with no success...

Any ideas?

2 Answers 2

45

The default types that the json package Unmarshals into are shown in the Unmarshal function documentation

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

Since you're unmarshaling into an interface{}, the returned types will only be from that set. The json package doesn't know about Something1 and Something2. You either need to convert from the map[string]interface{} that the json object is being unmarshaled into, or unmarshal directly into the struct type you want.

If you don't want to do unpack the data from a generic interface, or somehow tag the data so you know what type to expect, you could iteratively take the json and try to unmarshal it into each type you want.

You can even pack those into a wrapper struct to do the unmarshaling for you:

type Something1 struct {
    Thing      string `json:"thing"`
    OtherThing int64  `json:"other_thing"`
}

type Something2 struct {
    Croc  int  `json:"croc"`
    Odile bool `json:"odile"`
}

type Unpacker struct {
    Data       interface{}
}

func (u *Unpacker) UnmarshalJSON(b []byte) error {
    smth1 := &Something1{}
    err := json.Unmarshal(b, smth1)

    // no error, but we also need to make sure we unmarshaled something
    if err == nil && smth1.Thing != "" {
        u.Data = smth1
        return nil
    }

    // abort if we have an error other than the wrong type
    if _, ok := err.(*json.UnmarshalTypeError); err != nil && !ok {
        return err
    }

    smth2 := &Something2{}
    err = json.Unmarshal(b, smth2)
    if err != nil {
        return err
    }

    u.Data = smth2
    return nil
}

http://play.golang.org/p/Trwd6IShDW

8
  • That's my problem, I don't know what type I'm getting, "under" the string. So the secound option is not good. About the first one, how can I convert the map[string]interface{} if I dont know what key to use? @JimB
    – Blue Bot
    Feb 23, 2016 at 17:29
  • @darthydarth: What you do you mean "under the string"? In the map? play.golang.org/p/0zZ8fsmO17
    – JimB
    Feb 23, 2016 at 17:56
  • EDIT: Sorry just commented now before looking at your playground solution. That is exactly what I was missing! thank you! Please post it as an solution for others and I'll up-vote. Thanks again @JimB
    – Blue Bot
    Feb 23, 2016 at 19:42
  • 1
    @darthydarth: You're not getting a struct, you can only get one of those 6 default types when unmarshaling into an interface{}, and you can't assert an interface to a type that it isn't. Take the data out of the map you're getting and create a new struct of the type you want.
    – JimB
    Feb 23, 2016 at 19:59
  • 1
    @darthydarth: a type assertion only asserts that in interface contains a specific type; you can't change the type it contains. The range statement doesn't change anything, it was just an easy way to display the contents of the map.
    – JimB
    Feb 23, 2016 at 20:14
26

You have encountered a typical json vs typed language problem! Since json is untyped and schemaless, it is not possible to infer what data is "under the string" without actually decoding it.

So your only option is to unmarshal into an interface{} which always produces a map[string]interface{}. You could do some reflection magic here to build the final struct, but that's a lot of manual work and error prone. Here are some possible solutions:

Quick 'n' dirty

Let the json package do the reflection stuff. Attempt to unmarshal into every expected type:

func typeAssert(msg string) {

 var thing1 Something1

 err := json.Unmarshal([]byte(msg), &thing1)
 if err == nil{
    // do something with thing1
    return
 }    

 var thing2 Something2

 err = json.Unmarshal([]byte(msg), &thing2)
 if err == nil{
    // do something with thing2
    return
 }    

 //handle unsupported type

}

Build your own "type system" on top of json

Defer the encoding until you know what's inside. Use this struct as an intermediate representation of your data:

type TypedJson struct{
  Type string 
  Data json.RawMessage
}

Marshal:

thing := Something1{"asd",123}
tempJson, _ := json.Marshal(thing)

typedThing := TypedJson{"something1", tempJson}
finalJson, _ := json.Marshal(typedThing)

Unmarshal:

func typeAssert(msg string) {

  var input TypedJson  
  json.Unmarshal([]byte(msg), &input)

  switch input.Type{
  case "something1":
    var thing Something1
    json.Unmarshal(input.Data, &thing)
    queueStatsRes(thing)   
   case "something2":
    var thing Something2
    json.Unmarshal(input.Data, &thing)
    queueStatsRes(thing)
  default:
    //handle unsupported type
}

Use a typed serialization format

6
  • Liked the first solution, its exactly as you named it...but still will do the job perfectly. The second one is not that practical because in real life I have a very large struct constructed out of lots of other complex structs used by many places in the program so building a struct just to name the transferred main struct seems wrong to me and not pretty at all.
    – Blue Bot
    Feb 23, 2016 at 20:23
  • 1
    @darthydarth This "wrapper struct" will just be used for sending and receiving data. You can still use the original structs in the program. I think it's the better solution, but you are of course free to choose what fit's your case best.
    – fl0cke
    Feb 23, 2016 at 20:28
  • I do agree in a way, yet it still looks weird to me specifying the type in a string. I mite be wrong about that. Still, thanks for both solutions- upvoted
    – Blue Bot
    Feb 23, 2016 at 20:46
  • 2
    @darthydarth The Type could be anything that qualifies as an identifier (e.g. distinct int values). It looks weird because it really is just a hack to get around the limitations of json.
    – fl0cke
    Feb 23, 2016 at 20:58
  • yep a hack indeed, it's ok, I just really hate adding to many objects to a type if its not necessary. In this guess you are right
    – Blue Bot
    Feb 23, 2016 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.