繁体   English   中英

带有 json 接口的结构

[英]Struct with interface to json

我在问自己我遇到的错误。 我正在制作一个 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
}

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

在 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

暂无
暂无

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

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