登录
首页 >  Golang >  Go问答

如何将不同结构类型的数据编组到同一字段的 JSON 中?

来源:stackoverflow

时间:2024-03-05 15:54:24 311浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《如何将不同结构类型的数据编组到同一字段的 JSON 中?》,涉及到,有需要的可以收藏一下

问题内容

我有一个在公共包中定义的响应结构,如下所示。

package main

import (
    "encoding/json"
    "fmt"
)

type response struct {
    id string `json:"id,omitempty"`
    //all other int/string fields

    nestedobj *nested `json:"nested,omitempty"`
}

type nested struct {
    //field causing the issue.
    extendedstring string `json:"extended,omitempty"` //some user will need/expect a string

    //other user need extended json field as a different object
    extended *extended `json:"extended,omitempty"` //changing json:extended to other json:extended1 will work as expected
                                                    //but need to have the same field name containing object or just a string field
}

type extended struct {
    otherfield string `json:"another,omitempty"`
}

func main() {
    response := &response{id: "unique_id"}

    response.nestedobj = &nested{}

    //part 1
    response.nestedobj.extendedstring = "value"

    b, err := json.marshal(response)
    if err != nil {
        fmt.println(err)
    }
    fmt.println(string(b))
    //part 1 end

    
    response1 := &response{id: "unique_id"}

    response1.nestedobj = &nested{}

    //part 2
    response1.nestedobj.extended = &extended{}

    response1.nestedobj.extended.otherfield = "value"

    b1, err := json.marshal(response1)
    if err != nil {
        fmt.println(err)
    }
    fmt.println(string(b1))
    //part 2 end
    
    //either part 1 or 2 will be set for user type as per preference/flag/condition. 

}


现在,由于我在结构中使用了指针,所以不导出 json 中的任何空字段/对象,我想表现得像 当我将 extendedstring 设置为某个字符串值并省略 extended 自定义结构时,我的 json 应该如下所示

{"id":"unique_id",...other json fields..., "nested":{"extended": "value"}}

但是当我设置 extended 结构忽略 extendedstring 时,我应该得到 json

{"id":"UNIQUE_ID",...other json fields..., "nested":{"extended": {"another":"value"}}}

可以肯定的是,根据用户偏好(ifswitch 条件),在编组 json 中需要其中任何一个,因为它们必须具有字段名称 extended ,它可以是字符串或包含其他内容的 json 对象字段。

是否可以在不复制主结构的情况下实现这一目标?


解决方案


json.marshal 将调用您的类型 marshaljson 方法(如果存在)。使用它,您可以检查您的条件,然后返回相应的 json。

package main

import (
    "fmt"
    "encoding/json"
)

type ExtendedObj struct {
    Value string `json:"another"`
}

type Extended struct {
    str string
    Obj ExtendedObj `json:"extended"`
}

func (e* Extended) MarshalJSON() ([]byte, error) {
    if e.str != "" {
        return json.Marshal(struct {
            Value string `json:"extended"`
        }{e.str})
    }
    
    return json.Marshal(e)
}

func main() {
    v1 := Extended{"Hey!", ExtendedObj{}}
    jsonBytes, err := json.Marshal(&v1)
    
    if err != nil {
        fmt.Println("Error", err)
    }
    
    fmt.Println(string(jsonBytes))
    
    v2 := Extended{"", ExtendedObj{"Hey!"}}
    jsonBytes2, err := json.Marshal(v2)
    
    fmt.Println(string(jsonBytes2))
}

理论要掌握,实操不能落!以上关于《如何将不同结构类型的数据编组到同一字段的 JSON 中?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

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