【问题标题】:Struct with interface to json带有 json 接口的结构体
【发布时间】:2016-05-18 13:04:46
【问题描述】:

我在问自己遇到了一个错误。我正在制作一个 API,它发送一个看起来像这样的响应:

var StatusBack struct {
    Description string // to describe the error/the result
    StatusId int // the status number (500 Internal error, 200 OK...)
}
// client get 
{
    description: "{surname: \"Xthing\", firstname: \"Mister\"}"
    status_id: 200
}

所以我的想法是使用 Marshal 将 json 转换为字符串,然后 Marshal 第二次使用 StatusBack 结构发送它。但是,它并没有使我真正想要的是获取包含另一个对象的对象。客户端只得到一个包含字符串的对象。问题是,我不只发送用户作为结果,所以就像我在下面展示的那样,我认为我需要一个接口

var StatusBack struct {
    Description string // to describe the error
    Result <Interface or object, I don t know> // which is the result
    StatusId int // the status number (500 Internal error, 200 OK...)
}
// client get 
{
    description: "User information",
    result: {
        surname: "Xthing",
        firstname: "Mister"
    },
    status_id: 200
}

就像我之前说的,我不只是发送用户,它可能是很多不同的对象,那么我该如何实现呢?我的第二个想法更好吗?如果是,我该如何编码?

【问题讨论】:

    标签: json go struct


    【解决方案1】:

    在 golang 中,json.Marshal 处理嵌套结构、切片和映射。

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Animal struct {
        Descr description `json:"description"`
        Age   int         `json:"age"`
    }
    
    type description struct {
        Name string `json:"name"`
    }
    
    func main() {
        d := description{"Cat"}
        a := Animal{Descr: d, Age: 15}
        data, _ := json.MarshalIndent(a,"", "  ")
        fmt.Println(string(data))
    }
    

    此代码打印:

    {
      "description": {
        "name": "Cat"
      },
      "age": 15
    }
    

    当然,解组的工作方式完全相同。 如果我误解了这个问题,请告诉我。

    https://play.golang.org/p/t2CeHHoX72

    【讨论】:

    • 嗯我不会说你误解了,也许我没有说对我的问题;)这是一个 API,所以我的结构是客户端的答案好吗?这个结构包含另一个结构,它可以是任何结构类型(用户、动物、银行账户等),所以你的答案对 50% 的问题都有好处;)现在,如果我们以你为例,我该如何描述作为随机类型?还是接口类型?能够输入有关动物的名称或类型或大小等?
    • 是的,你可以,我更改了 Descr 的类型,它工作得非常好(见上文)。这样您就可以将任何内容放入 Descr 字段中。
    • 完美 ;) 谢谢!
    猜你喜欢
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多