dtef9322 2019-08-28 18:05
浏览 51
已采纳

在必需的JSON参数中包装和编组Go结构

I'm trying to create JSON to send to a Rails API that accepts the following format:

{"device":{"ipaddress":"192.168.1.2", "netmask": "255.255.255.0", "gateway": "192.168.1.1"}}

But I'm unsure of how to wrap what I've already marshaled into the "device":{} portion that the API accepts.

Here's what I have so far:

type Device struct {
    IPAddress string `json:"ipaddress"`
    Network   string `json:"network"`
    Gateway   string `json:"gateway"`
}

// gathers the IP info
func GatherIPInfo() {

    d := Device{
        IPAddress: "192.168.1.2",
        Network:   "255.255.255.0",
        Gateway:   "192.168.1.1",
    }

    // now send to API
    data, _ := json.Marshal(d) // looks like: {"ipaddress":"192.168.1.2","network":"255.255.255.0","gateway":"192.168.1.1"}

    ...
    ...
}

Do I have to create another struct to be able to achieve wrapping the existing into 'device' or is there an easier way?

Thanks!

  • 写回答

1条回答 默认 最新

  • dragonlew9876 2019-08-28 18:10
    关注

    You can create another struct to enclose the Device struct you have, or do something like this:

    json.Marshal(map[string]interface{}{"device":d})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog