dongtang1910 2016-05-18 13:04
浏览 14
已采纳

Golang-具有json接口的结构

I'm asking myself about an error that I got.. I'm making an API which send a response which seems like it:

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
}

So my idea was to make a json into a string with Marshal and then, Marshal a second time the StatusBack struct to send it. However, it doesn't make what I really want which is to get an object which contain another object. The client only get one object which contain a string..The thing is, I don't send only user as result, so like I show below I think I need an interface

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
}

Like I said before, I not only send user, it could be lot of different object, so how can I achieves it? Does my second idea is better? If yes, how can I code it?

Thank !

  • 写回答

1条回答 默认 最新

  • douyin2883 2016-05-18 13:17
    关注

    In golang, json.Marshal handles nested structs, slices and maps.

    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))
    }
    

    This code prints:

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

    Of course, unmarshalling works the exact same way. Tell me if I misunderstood the question.

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里