Eliad
Eliad

Reputation: 39

How do I create a generic function which converts json string into a struct in golang?

First of all, I have the folowing struct:

type User struct {
    Username string
    Password string
    FullName string
    Mail string
}

And I have tried to create the folowing function:

func FromJson(emptyJsonAble interface{},jsonString string) interface{} {
    err := json.Unmarshal([]byte(jsonString), &emptyJsonAble)
    if err != nil {
        panic(err)
    }
    return emptyJsonAble
}

I have called to the function in the folowing way:

user := FromJson(User{}, str)

But the function returns the folowing map instead of User struct:

map[FullName:a Mail:a Password:b Username:a]

How do I return the struct itself (witout converting the returned object every time)?

In other words, how to make the function to consider emptyJsonAble as User type when give. I have tryed to work with reflect.Type, but I'm stuck

Upvotes: 0

Views: 697

Answers (1)

Raymond Jones
Raymond Jones

Reputation: 112

When you pass the User struct through, you are effectively passing it a copy of the value, in your scenario what you want to do is pass a pointer reference to the type. Then, because you already have a pointer, you do not need to pass by reference inside of your function:

user := FromJson(&User{}, str)

err := json.Unmarshal([]byte(jsonString), emptyJsonAble)

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

UPDATE:

equally, because you are now passing by reference, you do not need to return a copy of the unmarshalled data struct:

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

In both cases, we can see the results are the same, so your return of the data is unnecessary

Upvotes: 1

Related Questions