[英]How do I Change the Position of Golang Struct Values?
我将如何更改 json 值的位置?
我试图实现的目标:
[{"key":"f","value":"f"},{"value":"f","key":"f"}]
问题:
type Struct struct {
Key string `json:"key"`
Value string `json:"value"`
}
func main() {
test := []Struct{ {Key: "test",Value: "wep"}, {Value: "wep",Key: "test"}}
bytes, _ := json.Marshal(test)
fmt.Print(string(bytes))
}
运行此代码打印[{"key":"test","value":"wep"},{"key":"test","value":"wep"}]
我也试过做这样的事情,但它只是打印空值
type Struct struct {
Key string `json:"key"`
Value string `json:"value"`
Value2 string `json:"value"`
Key2 string `json:"key"`
}
但是我如何能够切换键和值字段的位置呢?
对于“我可以让单个结构类型以不同的顺序或不同的场合序列化其字段吗?”的问题? :
没有一种简单的方法可以做到这一点。
关于结构域:您编写的代码以给定的顺序显示了分配操作,但是一旦您的代码被编译,就不再有该顺序的痕迹。
如果你真的需要这个(旁注:我很想知道你的用例?),你可以创建一个自定义类型,使用它自己的.MarshalJSON()
方法,它会保存一个值,指示“字段应该在这个命令”。
如果您需要发送异构对象数组,请使用单独的结构类型和[]interface{}
数组:
type Obj1 struct{
Key string `json:"name"`
Value string `json:"value"`
}
type Obj2 struct{
Value string `json:"value"`
Key string `json:"name"`
}
func main() {
test := []interface{}{ Obj1{Key: "test",Value: "wep"}, Obj2{Value: "wep",Key: "test"}}
bytes, _ := json.Marshal(test)
fmt.Print(string(bytes))
}
如果您使用json.Marshal
提供官方的包是不是允许通过这样做。 MarhalJSON
,您可以实现自己的MarhalJSON
方法,以便您可以决定结构字段的位置。
type StructA struct {
Key string `json:"key"`
Value string `json:"value"`
}
type StructB struct {
Value string `json:"value"`
Key string `json:"key"`
}
func main() {
test := []interface{}{
StructA{Key: "test", Value: "wep"},
StructB{Value: "wep", Key: "test"},
}
bytes, _ := json.Marshal(test)
fmt.Print(string(bytes))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.