将Go中的结构体映射转换为JSON格式。

huangapple go评论88阅读模式
英文:

Jsonify map of structs in Go

问题

现在我有一个用于客户端连接的结构体,如下所示:

type ClientConn struct {
    uuid      string
    websocket *websocket.Conn
    ip        net.Addr
    longitude float64
    latitude  float64
}

我还有一个ClientConn的映射表,如下所示:

var clientList = make(map[string]*ClientConn)

所以每次连接时,我都会将一个新的ClientConn添加到clientList中,但我想做的是将clientList转换为JSON,并获取一个包含其值和键的ClientConn数组,而不仅仅是键。

如果我执行以下操作:

json.Marshal(clientList)

那么我只会得到带有空对象的键,而我想要获取的是包含值和键的完整ClientConn结构体数组。

有什么方法可以做到这一点?

英文:

So right now I have a struct for client connections which looks as following

type ClientConn struct {
    uuid      string
    websocket *websocket.Conn
    ip        net.Addr
    longitude float64
    latitude  float64
}

and I've also got a map of ClientConn as following

var clientList = make(map[string]*ClientConn)

so I add a new ClientConn on each connection to the clientList but what I'm trying to do is jsonify the clientList and obtain an array of ClientConn with its values and not just keys.

If I do

json.Marshal(clientList)

then I just get the keys with a empty object and what I'd like to retrieve is the whole ClientConn struct array with the values and keys.

What would be a way to do this?

答案1

得分: 3

这是 [tag:go] 标签的每日问题。

你的结构字段必须是可导出的,也就是以大写字母开头。

关于在 Go 中解析 JSON 的好文章是官方博客上的 JSON and Go

对于任何对 Go 感兴趣的人来说,Effective Go 是必读的。

英文:

This is the daily question of the [tag:go] tag.

Your struct fields has to be exported, aka start with an uppercase letter.

A good read to explain json with go is JSON and Go on the official blog.

A must-read for anyone interested in Go is Effective Go.

huangapple
  • 本文由 发表于 2014年10月9日 22:43:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/26281366.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定