登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-03-16 18:33:29 152浏览 收藏

在 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 的 b.y,正如预期的那样。但是,如果我再次将其重新编组为 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
        }
    ]
}

解决方案


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

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

今天关于《如何使用结构的类型而不是 go 中的标签重新编组结构?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>