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>

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

报告相同问题?

悬赏问题

  • ¥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 悬赏!微信开发者工具报错,求帮改