douer9399 2014-07-11 20:30
浏览 81
已采纳

Golang jsonable指向切片中不同结构的指针

My golang program have this structure of structs:

type JSONDoc struct {
     Count  int         `json:"count"`
     Objects []uintptr  `json:"objects"`
}

type ObjectA struct {
     FieldA string
}

type ObjectB struct {
     FieldB string
}

I don't know what object types can be in JSONDoc.Objects, i'm need to store multiple structs in json array. Reflect returns pointers to structs, i'm appending them to struct, but encoding/json package in result json replace pointer with integer address. Also unsafe.Pointer cannot be parsed by encoding/json too.

Just want result json to look as

{
     "count":2, 
     "objects":
     [
         {"FieldA":"..."}, 
         {"FieldB":"..."}
     ]
}

How can i store pointers to structs that will be correctly encoded to json?

  • 写回答

1条回答 默认 最新

  • douzhanshen0657 2014-07-11 20:42
    关注

    You could use interface{}, for example :

    type JSONDoc struct {
        Count   int           `json:"count"`
        Objects []interface{} `json:"objects"`
    }
    
    func main() {
        doc := JSONDoc{Count: 2}
        doc.Objects = append(doc.Objects, &ObjectA{"A"}, &ObjectB{"B"}) 
        b, err := json.MarshalIndent(&doc, "", "\t")
        fmt.Println(string(b), err)
    }
    

    <kbd>playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成