I've seen some similar question(Same method on different array types in Go)
But in my case my functions do not return same types.
Can you write the below code more simply?
package main
import (
"encoding/json"
"fmt"
)
type A struct {
Name string `json:"name"`
Age int `json:"age"`
}
type B struct {
Name string `json:"name"`
Age int `json:"age"`
Address string `json:address`
}
func UnmarshalA(b []byte) *A {
var t *A
_ = json.Unmarshal(b, &t)
return t
}
func UnmarshalB(b []byte) *B {
var t *B
_ = json.Unmarshal(b, &t)
return t
}
func main() {
a := []byte(`{"name": "aaaa", "age": 1}`)
unmarshal_a := UnmarshalA(a)
fmt.Println(unmarshal_a.Name)
b := []byte(`{"name": "bbbb", "age": 2, "address": "b@example.com"}`)
unmarshal_b := UnmarshalB(b)
fmt.Println(unmarshal_b.Name)
}
// aaaa
// bbbb
You have a couple of options.
Don't bother using UnmarshalA
and UnmarshalB
. They're really not doing much and you're really only abstracting away a single line... var t *A
If you don't actually need the A
and B
structs and simply want the contents of the JSON string represented in a way you can use it, you could just unmarshal into a map[string]interface{}
.
E.g.
package main
import (
"encoding/json"
"fmt"
)
func UnmarshalAny(b []byte) map[string]interface{} {
var t = make(map[string]interface{})
_ = json.Unmarshal(b, &t)
return t
}
func main() {
a := []byte(`{"name": "aaaa", "age": 1}`)
unmarshal_a := UnmarshalAny(a)
b := []byte(`{"name": "bbbb", "age": 2, "address": "b@example.com"}`)
unmarshal_b := UnmarshalAny(b)
// Accessed like this...
fmt.Println(unmarshal_a["name"])
fmt.Println(unmarshal_b["name"])
}
https://play.golang.org/p/KaxBlNsCDR
If you wanted to pass the data by reference then you would change it to something like this:
package main
import (
"encoding/json"
"fmt"
)
func UnmarshalAny(b []byte) *map[string]interface{} {
var t = make(map[string]interface{})
_ = json.Unmarshal(b, &t)
return &t
}
func main() {
a := []byte(`{"name": "aaaa", "age": 1}`)
unmarshal_a := UnmarshalAny(a)
b := []byte(`{"name": "bbbb", "age": 2, "address": "b@example.com"}`)
unmarshal_b := UnmarshalAny(b)
// Accessed like this...
fmt.Println((*unmarshal_a)["name"])
fmt.Println((*unmarshal_b)["name"])
}