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>

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?