Sredny M Casanova
Sredny M Casanova

Reputation: 5063

getting: Cannot unmarshal string into Go value

am having some troubles unmarshalling some content into a struct object in go. Basically, my struct is defined as:

 type TheParam struct {
    Id       string `json:"id,string"`
    Provider string `json:"provider,string"`
}

Now, I have one variable with the bytes, if I make fmt.Print(string(data)) then I get:

"{\"id\":\"some-id\",\"provider\":\"any-provider\"}"

An example of he data in bytes is:

34 123 92 34 105 100 92 34 58 92 34 103 105 116 104 117 98 45 100 97 115 104 45 97 99 99 101 115 115 92 34 44 92 34 112 114 111 118 105 100 101 114 92 34 58 92 34 103 105 116 104 117 98 92 34 125 34

And, am making the unmarshalling with:

if err = json.Unmarshal(data, &myParam); err != nil {
        redisLogger.WithError(err).Error("unmarshalling into interface")
    }

So, now am getting: json: cannot unmarshal string into Go value of type TheParam. What am I missing?

Upvotes: 0

Views: 11296

Answers (2)

Pavlo Strokov
Pavlo Strokov

Reputation: 2087

The string itself is encoded json value, so first you need to decode it into a string and then decode this value into the struct: https://play.golang.org/p/qSOd1O9fOSQ

Also please pay attention to the changed tags of the struct type. You don't need to use type specification in tag. It would be defined for you automatically.

Upvotes: 2

lwolf
lwolf

Reputation: 484

The string struct tag is redundant as you already defined the type in the struct.

This Playground should work:

https://play.golang.org/p/NixyNSHOK8w

Upvotes: 1

Related Questions