首页 > 解决方案 > 如何使用结构的类型而不是 go 中的标签重新编组结构?

问题描述

我想将结构重新编组为 json,并使用结构中定义的类型作为输出。结构:

type A struct{
B []B //edit: fields have to be exported to work
}

type B struct{
X string `json:"x"` //edit: fields have to be exported to work
Y float64 `json:"y,string"` //edit: fields have to be exported to work
Z float64 `json:"z,string"` //edit: fields have to be exported to work

如果使用这些结构解组,我会得到 By 作为 float64,正如预期的那样。但是,如果我再次将其重新编组为 JSON,我会得到我解组的 JSON,其中 y 和 z 作为字符串,但我想将它们作为 float64。我必须添加 ',string' 部分,因为 API 在 JSON 响应中将所有内容都作为字符串返回(参见下面的示例)。我是否必须编写一个自定义编组函数来执行此操作,或者我可以将 json 标记添加到结构定义中吗?

示例响应和重新编组的 json:

{
    "A": [
        {
            "x": "test1",
            "y": "1.00",
            "z": "1.01"
        },
        {
            "x": "test2",
            "y": "2.00",
            "z": "2.01"
        }
    ]
}

预期的重新编组 JSON:

{
    "A": [
        {
            "x": "test1",
            "y": 1.00,
            "z": 1.01
        },
        {
            "x": "test2",
            "y": 2.00,
            "z": 2.01
        }
    ]
}

标签: jsongostruct

解决方案


您根本无法编组或解组这些字段,因为这些字段未导出。但是要执行您所描述的操作,只需转换为没有(或不同)结构标记的等效类型。因为它是一个嵌套切片,所以您必须对其进行迭代。

func main() {
    a := A{}
    err := json.Unmarshal(corpus, &a)
    if err != nil {
        panic(err)
    }
    c := C{}
    for _, b := range a.B {
        c.B = append(c.B, D(b))
    }
    payload, _ := json.Marshal(c)
    fmt.Println(string(payload))
}

type A struct {
    B []B
}

type B struct {
    X string  `json:"x"`
    Y float64 `json:"y,string"`
    Z float64 `json:"z,string"`
}

type C struct {
    B []D
}

type D struct {
    X string  `json:"x"`
    Y float64 `json:"y"`
    Z float64 `json:"z"`
}

工作场所示例: https: //play.golang.org/p/pQTcg0RV_RL


推荐阅读