登录
首页 >  Golang >  Go问答

手动在golang中将struct转换为json对象

来源:stackoverflow

时间:2024-02-06 17:39:46 423浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《手动在golang中将struct转换为json对象》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我有一个结构可以说

type Foo struct {
  A string `json:",omitemtpy"
}

我知道我可以使用类似的东西轻松地将其转换为 json

json.Marshal(Foo{})

它将返回一个空的 json 字符串。

但我需要使用相同的结构返回结构的 json 表示形式,其中包含所有字段和 json 中存在的“空值”。 (实际上,它是一个非常大的结构,所以我不能只保留没有标签的副本)

最简单的方法是什么?

基本上,我需要创建一个忽略 json omitempty 标签的结构的 json 编组。

此 json 创建不需要高效或高性能。

我更希望有一个库可以用于此类任务,但我见过的大多数库要么创建一些特殊格式,要么尊重 omitempty

编辑:

选择 https://stackoverflow.com/a/77799949/2187510 作为我的答案,并进行一些额外的工作以允许默认值(使用其代码作为参考)

defaultFoo := FoodWithPts{ Str: "helloWorld"}
dupFooType := dupType(reflect.TypeOf(defaultFoo))
foo := reflect.Zero(dupFooType).Interface()

// New additions
defaults, _ := json.Marshal(defaultFoo)
json.Unmarshal(defaults, &foo)   // overwrites foo with defaults
// End New additions

data, err := json.Marshal(foo)
fmt.Println("dup FooWithPtrs:\n", string(data), err)

输出:

dup FooWithPtrs:
    {"String":"helloWorld","Int":0,"Bar":null} 

正确答案


您无法在运行时修改标签,但可以使用 $$c 在运行时创建结构类型$$reflect.StructOf()

因此,我们的想法是复制结构类型,但在重复中从 JSON 标记中排除 ,omitempty 选项。

您可以在 Go Playground 上找到以下所有示例。

这比人们一开始想象的要容易。我们只需要递归地执行(一个结构体字段可能是另一个结构体),并且我们绝对应该处理指针:

func dupType(t reflect.Type) reflect.Type {
    if t.Kind() == reflect.Pointer {
        return reflect.PointerTo(dupType(t.Elem()))
    }

    if t.Kind() != reflect.Struct {
        return t
    }

    var fields []reflect.StructField

    for i := 0; i < t.NumField(); i++ {
        sf := t.Field(i)
        sf.Type = dupType(sf.Type)
        // Keep json tag but cut ,omitempty option if exists:
        if tag, _ := strings.CutSuffix(sf.Tag.Get("json"), ",omitempty"); tag == "" {
            sf.Tag = ""
        } else {
            sf.Tag = `json:"` + reflect.StructTag(tag) + `"`
        }
        fields = append(fields, sf)
    }

    return reflect.StructOf(fields)
}

让我们用这种类型来测试它:

type Foo struct {
    Str string `json:"String,omitempty"`
    Int int    `json:",omitempty"`
    Bar struct {
        Float  float64 `json:",omitempty"`
        PtrInt int     `json:",omitempty"`
        Baz    struct {
            X int `json:"XXXX,omitempty"`
        } `json:",omitempty"`
    } `json:",omitempty"`
}

首先,这是没有类型重复的 JSON 输出:

data, err := json.Marshal(Foo{})
fmt.Println("Foo:\n", string(data), err)

输出:

Foo:
 {"Bar":{"Baz":{}}} 

请注意,我们得到了 BarBaz 字段,因为它们是结构体。

让我们尝试类型复制:

dupFooType := dupType(reflect.TypeOf(Foo{}))
foo := reflect.Zero(dupFooType).Interface()

data, err := json.Marshal(foo)
fmt.Println("dup Foo:\n", string(data), err)

这将输出:

dup Foo:
 {"String":"","Int":0,"Bar":{"Float":0,"PtrInt":0,"Baz":{"XXXX":0}}} 

不错!正是我们想要的!

但我们还没有完成。如果我们有一个带有结构指针字段的类型怎么办?像这样:

type FooWithPtrs struct {
    Str string `json:"String,omitempty"`
    Int int    `json:",omitempty"`
    Bar *struct {
        Float  float64 `json:",omitempty"`
        PtrInt int     `json:",omitempty"`
        Baz    *struct {
            X int `json:"XXXX,omitempty"`
        } `json:",omitempty"`
    } `json:",omitempty"`
}

尝试对重复类型的值进行 JSON 编组:

dupFooType := dupType(reflect.TypeOf(FooWithPtrs{}))
foo := reflect.Zero(dupFooType).Interface()

data, err := json.Marshal(foo)
fmt.Println("dup FooWithPtrs:\n", string(data), err)

输出:

dup FooWithPtrs:
 {"String":"","Int":0,"Bar":null} 

如果结构包含指针,则这些指针在 JSON 输出中显示为 null,但我们也希望它们的字段也出现在输出中。这需要将它们初始化为非 nil 值,以便它们生成输出。

幸运的是,我们还可以使用反射来做到这一点:

func initPtrs(v reflect.Value) {
    if !v.CanAddr() {
        return
    }

    if v.Kind() == reflect.Pointer {
        v.Set(reflect.New(v.Type().Elem()))
        v = v.Elem()
    }

    if v.Kind() == reflect.Struct {
        for i := 0; i < v.NumField(); i++ {
            initPtrs(v.Field(i))
        }
    }
}

我们很兴奋!让我们看看实际效果:

dupFooType := dupType(reflect.TypeOf(FooWithPtrs{}))
fooVal := reflect.New(dupFooType)
initPtrs(fooVal.Elem())

data, err := json.Marshal(fooVal.Interface())
fmt.Println("dup and inited FooWithPtrs:\n", string(data), err)

输出:

dup and inited FooWithPtrs:
 {"String":"","Int":0,"Bar":{"Float":0,"PtrInt":0,"Baz":{"XXXX":0}}} 

不错!它包含所有字段!

本篇关于《手动在golang中将struct转换为json对象》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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