Golang Json解包到包含接口的结构{}

时间:2018-10-06 23:49:58

标签: json go

我对包含接口{}的结构具有json解组要求。内部类型仅在运行时才知道,因此该结构是使用interface {}定义的。但是,在传递给json.Unmarshal之前,该类型已正确填充。但是json.Unmarshal始终使用map []而不是给定类型填充结果结构。 我如何解决此问题以获得正确的解组行为。

在此处查看简单的测试代码和行为:

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\n", o)

    fmt.Printf("js: %s\n", js)

    er := json.Unmarshal(js, &o)
    fmt.Printf("er: %+v\n", er)

    fmt.Printf("o: %+v\n", o)

}

结果:

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

1 个答案:

答案 0 :(得分:2)

您可以创建一个包含预期类型的​​辅助one类型。从该辅助类型转换回常规one类型。

即(play link):

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\n", o)

    fmt.Printf("js: %s\n", js)

    var oStatic oneStatic
    er := json.Unmarshal(js, &oStatic)
    fmt.Printf("er: %+v\n", er)

    o = one{oStatic.S, oStatic.Res}
    fmt.Printf("o: %+v\n", o)

}