当前位置: > > > > 在编组到 JSON 之前将结构转换为不同的结构
在编组到 JSON 之前将结构转换为不同的结构
来源:stackoverflow
2024-04-24 16:57:35
0浏览
收藏
Golang不知道大家是否熟悉?今天我将给大家介绍《在编组到 JSON 之前将结构转换为不同的结构》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!
问题内容
我正在尝试使用 go 作为后端来实现一个棋盘游戏,但遇到了一些障碍,我试图了解在 go 中解决这个问题的最佳方法是什么。
我有一个复杂的结构,它代表我在游戏引擎中使用的游戏状态,用于评估状态以及每个动作将执行的操作以及它将如何影响游戏。
type game struct {
id string
name string `json:"name"`
version version `json:"version"`
startingmode startingmode `json:"startingmode"`
players []*player `json:"players"`
gamemap *boardmap `json:"gamemap"`
countries map[string]*country `json:"countries"`
config *config `json:"config"`
turnplayer *player `json:"turnplayer"` //represents the player who started the turn
turncountry *country `json:"turncountry"` //represents the country which started the turn
currentplayer *player `json:"currentplayer"` //represents the current player to action
gamestart bool `json:"gamestart"`
gamefinish bool `json:"gamefinish"`
inauction bool `json:"inauction"` //represents the game is in the auction stage
gamesettings settings `json:"settings"`
}
现在,我可以将其编组为 json 并将其保存在我的数据库中,它工作正常,但是当我必须将其发送到前端时,它实际上不起作用。而且前端不需要知道那么多信息,我真的想要一些更简单的东西,例如:
type OtherGame struct {
players []*OtherPlayer
countries []*OtherCountry
map []*OtherArea
}
所以,我想我必须编写一些转换器函数,然后封送这个 othergame 结构,或者我应该编写一个自定义函数来迭代 game 中的不同结构并使用 sprintf 将它们放入字符串中?
解决方案
我经常使用这种设计模式来为特定处理程序生成自定义输出。在那里定义您的 json 标签并仅公开您需要的内容。然后,自定义类型与您的处理程序紧密耦合:
func gamehandler(w http.responsewriter, r *http.request) {
g, err := dblookupgame(r) // handle err
// define one-time anonymous struct for custom formatting
jv := struct {
id string `json:"id"`
name string `json:"name"`
version string `json:"ver"`
}{
id: g.id,
name: g.name,
version: g.version,
}
err = json.newencoder(w).encode(&jv) // handle err
}
type game struct {
id string
name string
version string
secret string // don't expose this
// other internals ...
}
您可以编写一个 method 将 game 数据转换为 othergame。像这样的东西。
func (game game) othergame() othergame {
return othergame{
players: game.players,
countries: game.countries,
}
}
在发送到 front-end 之前调用此方法。
game := Game{...}
otherGame := game.OtherGame()
终于介绍完啦!小伙伴们,这篇关于《在编组到 JSON 之前将结构转换为不同的结构》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~米云公众号也会发布Golang相关知识,快来关注吧!
