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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测