我试图弄清楚是否有一种方法可以仅使用字符串和预期类型将 JSON 字符串解组为特定结构。到目前为止,这是我想出的。
代码
package main
import (
"encoding/json"
"fmt"
"reflect"
)
type Person struct {
Name string `json:"name"`
}
func genericUnmarshal(jsonString string, t reflect.Type) interface{} {
p := reflect.New(t)
result := p.Interface()
json.Unmarshal([]byte(jsonString), &result)
return result
}
func main() {
jsonData := "{\"name\":\"John\"}"
unmarshalledPerson := genericUnmarshal(jsonData, reflect.TypeOf(Person{}))
person := Person{Name: "John"}
fmt.Printf("struct value: %+v type: %+v\n", person, reflect.TypeOf(person))
fmt.Printf("unmarshalled value: %+v type: %+v\n", unmarshalledPerson, reflect.TypeOf(unmarshalledPerson))
fmt.Printf("are variables equal: %v\n", reflect.DeepEqual(unmarshalledPerson, person))
}
退货
struct value: {Name:John} type: main.Person
unmarshalled value: &{Name:John} type: *main.Person
are variables equal: false
该方法genericUnmarshal
返回一个指向该类型的指针。
我的问题:有没有办法将未编组的值更改为结构(即Person
)而不是指针,以便reflect.DeepEqual(unmarshalledPerson, person)
返回true
?