Logan Shire
Logan Shire

Reputation: 5103

JSON decode into struct as interface{} yields map[string]interface{}, not struct

Here is a go playground replicating the issue: https://play.golang.org/p/GgHsLffp1G

Basically, I'm trying to write a function that takes a struct and returns a function that can decode http requests as that type. Unfortunately some type information is being lost and the type being returned is a map[string]interface{} and not the correct struct type. How can I communicate the correct type to the JSON decoder? Would JSON unmarshal work better?

Upvotes: 2

Views: 714

Answers (1)

Sridhar
Sridhar

Reputation: 2532

This seems to work:

Playground

func requestParser(i interface{}) parser {
    return func(r io.Reader) (interface{}, error) {
        json.NewDecoder(r).Decode(i)
        return reflect.ValueOf(i).Elem(), nil
    }
}

func main() {
    var foo Foo
    s := "{\"Name\":\"Logan\"}"
    p := requestParser(&foo)
}

Upvotes: 1

Related Questions