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})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改