Last active
August 15, 2023 10:32
-
-
Save mecitsemerci/dd81283b7003b367c6a771fa480abcfb to your computer and use it in GitHub Desktop.
JSON serialize and deserialize using go generics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package jsonconvert | |
import "encoding/json" | |
func Deserialize[T any](str string) (T, error) { | |
var d T | |
err := json.Unmarshal([]byte(str), &d) | |
if err != nil { | |
return d, err | |
} | |
return d, nil | |
} | |
func Serialize(obj any) (string, error) { | |
d, err := json.Marshal(obj) | |
if err != nil { | |
return "", err | |
} | |
return string(d), nil | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output
{1001 Laptop}
{"id":1001,"name":"Laptop"}