Underneath encoding/json it uses relfect to encoding struct.
But How can I encoding something that is already a type of reflect.Value
Check out the code below:
type Person struct {
Name string `json:"name"`
Pwd string `json:"pwd"`
}
func main() {
factory := map[string]reflect.Type{
"Person":reflect.TypeOf(Person{}),
}
s := reflect.New(factory["Person"]).Elem()
s.Field(0).SetString("Max")
s.Field(1).SetString("Password")
j, err := json.Marshal(s)
if err != nil {
fmt.Println("error")
}
fmt.Println(j)
}
It out puts something like this:
[123 34 102 108 97 103 34 58 52 48 54 125]
What is these? What is correct way to do this, I mean to get right json string from a reflect.Value type?
Use (reflect.Value).Interface()
to get a value of type interface{}
which can be JSON-encoded:
j, err := json.Marshal(s.Interface())
As for your question:
[123 34 102 108 97 103 34 58 52 48 54 125]
is the string {"flag":406}
, printed as a slice of bytes (which is what json.Marshal
returns).