繁体   English   中英

如何使用结构的类型而不是 go 中的标签重新编组结构?

[英]How can I remarshal a struct using the types of the struct and not the tags in 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

如果使用这些结构解组,我将按预期作为 float64 获得 By。 但是,如果我再次将其重新编组为 JSON,则会得到解组的 JSON,其中 y 和 z 作为字符串,但我想将它们作为 float64。 我必须添加 ',string' 部分,因为 API 将所有内容作为 JSON 响应中的字符串返回(请参见下面的示例)。 我是否必须编写一个自定义的 marshal 函数来执行此操作,或者我可以将 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
        }
    ]
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM