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 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值