如何动态更改结构的json标签? [英] How do I dynamically change the struct's json tag?
问题描述
我有以下内容:
package main
import (
"encoding/json"
"fmt"
"os"
"reflect"
)
type User struct {
ID int64 `json:"id"`
Name string `json:"first"` // want to change this to `json:"name"`
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},
)
}
我正在尝试对结构进行json编码,但是在我需要更改json键之前,例如,最终的json应该如下所示:
I am trying to json encode the struct but before I do I need to change the json key...eg the final json should look like:
{"id": 1, "name": "Ken Jennings", "address": "123 Jennings Street"}
我注意到value.Type().Field(i).Tag.Get("json")的方法,但是没有设置方法.为什么?以及如何获得所需的json输出.
I noticed the method for value.Type().Field(i).Tag.Get("json"), however there is no setter method. Why? and how do I get the desired json output.
此外,我如何遍历所有字段,包括嵌入式结构Another?
Also, how do I iterate through all the fields, including the embedded struct Another?
https://play.golang.org/p/Qi8Jq_4W0t
推荐答案
这很麻烦,但是如果您可以将该结构包装在另一个结构中,并使用新的结构进行编码,则可以:
It's kludgy, but if you can wrap the struct in another, and use the new one for encoding, then you could:
- 编码原始结构
- 将其解码为
interface{}
以获得地图 - 替换地图键
- 然后对地图进行编码并返回
- Encode the original struct,
- Decode it to an
interface{}
to get a map - Replace the map key
- Then encode the map and return it
因此:
type MyUser struct {
U User
}
func (u MyUser) MarshalJSON() ([]byte, error) {
// encode the original
m, _ := json.Marshal(u.U)
// decode it back to get a map
var a interface{}
json.Unmarshal(m, &a)
b := a.(map[string]interface{})
// Replace the map key
b["name"] = b["first"]
delete(b, "first")
// Return encoding of the map
return json.Marshal(b)
}
在操场上: https://play.golang.org/p/TabSga4i17
这篇关于如何动态更改结构的json标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!