我对包含接口{}的结构具有json解组要求。 内部类型仅在运行时才知道,因此该结构是使用interface {}定义的。 但是,在传递给json.Unmarshal之前,该类型已正确填充。 但是json.Unmarshal始终使用map []而不是给定类型填充结果结构。
我如何解决此问题以获得正确的解组行为。
在这里查看简单的测试代码和行为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | package main import ( "fmt" // s"strings" "encoding/json" ) type one struct { S string `json:"status"` Res interface{} `json:"res"` } type two struct { A string B string } func main() { t := []two {{A:"ab", B:"cd",}, {A:"ab1", B:"cd1",}} o := one {S:"s", Res:t} js, _ := json.Marshal(&o) fmt.Printf("o: %+v ", o) fmt.Printf("js: %s ", js) er := json.Unmarshal(js, &o) fmt.Printf("er: %+v ", er) fmt.Printf("o: %+v ", o) } |
结果:
1 2 3 4 | o: {S:s Res:[{A:ab B:cd} {A:ab1 B:cd1}]} js: {"status":"s","res":[{"A":"ab","B":"cd"},{"A":"ab1","B":"cd1"}]} er: <nil> o: {S:s Res:[map[A:ab B:cd] map[B:cd1 A:ab1]]} |
在这里查看代码1
-
为什么要分配给已经包含值的相同变量
o 。 - @Himanshu Thats测试代码。 如果我封送处理一个对象结构,然后将其解组回同一个对象,则可以预期您应该将原始结构取回。 这里没有发生。
您可以创建一个辅助
即(播放链接):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | package main import ( "fmt" // s"strings" "encoding/json" ) type one struct { S string `json:"status"` Res interface{} `json:"res"` } type two struct { A string B string } type oneStatic struct { S string `json:"status"` Res []two `json:"res"` } func main() { t := []two{{A:"ab", B:"cd"}, {A:"ab1", B:"cd1"}} o := one{S:"s", Res: t} js, _ := json.Marshal(&o) fmt.Printf("o: %+v ", o) fmt.Printf("js: %s ", js) var oStatic oneStatic er := json.Unmarshal(js, &oStatic) fmt.Printf("er: %+v ", er) o = one{oStatic.S, oStatic.Res} fmt.Printf("o: %+v ", o) } |
- 谢谢! 上面的简单逻辑难道不是很麻烦吗? 但是为什么不能去使用给定的strcut并解压缩呢? 在我的示例代码中,如果我确实reflect.TypeOf(o.Res),它已经给了我正确的类型。 为什么API不能这样做?
-
我认为原因可能是函数
fmt.Printf() 不知道确切的用户定义类型。 它只能反映以获取基本类型,例如map,struct,int,string等。 - 它不是Printf,问题出在json.Unmarshal()中