douyi7055 2017-11-16 17:04
浏览 40
已采纳

将具有嵌入式接口的结构转换为JSON

I have a struct that I want to marshal to JSON. It has a defined field called Foo (exported as foo) and a data interface field to which I want to pass a dynamic struct with additional JSON fields.

However when the data field is an interface instead of the specific struct it never gets exported as JSON. How can I make this work?

package main

import (
    "encoding/json"
    "fmt"
)

type data interface{}

type foo struct {
    Foo string `json:"foo,omitempty"`
    data
}

type bar struct {
    Bar string `json:"bar,omitempty"`
}

func main() {
    b := bar{"bar"}
    f := foo{"foo", b}

    byt, err := json.Marshal(f)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(byt))
}

I need to output to look like this (it needs to be flat, not nested):

{"foo": "foo", "bar": "bar"}
  • 写回答

3条回答 默认 最新

  • duanmeng3573 2017-11-16 19:35
    关注

    You could do this with a custom json.Marshaler implementation and a little bit of byte slicing.

    func (f foo) MarshalJSON() ([]byte, error) {
        type goo foo
        g := goo(f)
    
        b1, err := json.Marshal(g)
        if err != nil {
            return nil, err
        }
    
        b2, err := json.Marshal(g.data)
        if err != nil {
            return nil, err
        }
    
        s1 := string(b1[:len(b1)-1])
        s2 := string(b2[1:])
    
        return []byte(s1 + ", " + s2), nil
    }
    

    https://play.golang.org/p/NYTNWIL-xu

    Please note that this is not checking whether the bytes can actually be sliced and it does also not consider the possible case of the data field being a slice or an array, which i'm unsure how you would want that flattened anyway.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题