I have the following:
package main
import (
"encoding/json"
"fmt"
"os"
"reflect"
)
type User struct {
ID int64 `json:"id"`
Name string `json:"first"`
tag string `json:"-"`
Another
}
type Another struct {
Address string `json:"address"`
}
func (u *User) MarshalJSON() ([]byte, error) {
value := reflect.ValueOf(*u)
for i := 0; i < value.NumField(); i++ {
tag := value.Type().Field(i).Tag.Get("json")
field := value.Field(i)
fmt.Println(tag, field)
}
return json.Marshal(u)
}
func main() {
anoth := Another{"123 Jennings Street"}
_ = json.NewEncoder(os.Stdout).Encode(
&User{1, "Ken Jennings", "name",
anoth},
)
}
I am trying to json encode the structure, but before I need to change the json key ... for example, the final json should look like this:
{"id": 1, "name": "Ken Jennings", "address": "123 Jennings Street"}
I noticed the value.Type () method. Field (i) .Tag.Get ("json"), however there is no setter method. What for? and how do I get the desired json output.
Also, how to iterate over all fields, including the inline structure? Still?
https://play.golang.org/p/Qi8Jq_4W0t
user776942
source
share