我尽量避免用简单的答案提问,但我似乎无法弄清问题是什么......(标题中的问题)
相关代码:
match := new(Match)
if _, msgB, err = ws.ReadMessage(); err != nil {
panic(err)
}else {
println(string(msgB))
err = json.Unmarshal(msgB, match)
if err != nil { panic(err) }
}
type Match struct {
Teams [][]Char
Map [][]Tile
ID string //uuid
Socket *websocket.Conn `json:'-'`
}
type Char struct {
ID int
HP int
CT int
Stats statList
X int
Y int
ACList Actions
}
type statList struct {
Str int
Vit int
Int int
Wis int
Dex int
Spd int
}
type Actions struct {
Actions []Action
TICKCT int
}
要解组的字符串(为可见性设置格式):
{
"Teams": [
[
{
"ID": 1,
"HP": 10,
"CT": 0,
"Stats": [
1,
1,
1,
1,
1,
1
],
"X": 0,
"Y": 0,
"ACList": {
"Actions": [],
"TICKCT": 0
}
}
],
[
{
"ID": 2,
"HP": 10,
"CT": 0,
"Stats": [
1,
1,
1,
1,
1,
1
],
"X": 2,
"Y": 2,
"ACList": {
"Actions": [],
"TICKCT": 0
}
}
]
],
"Map": [
[
{
"Depth": 1,
"Type": 1,
"Unit": 1
},
{
"Depth": 1,
"Type": 1,
"Unit": null
},
{
"Depth": 1,
"Type": 1,
"Unit": null
}
],
[
{
"Depth": 1,
"Type": 1,
"Unit": null
},
{
"Depth": 1,
"Type": 1,
"Unit": null
},
{
"Depth": 1,
"Type": 1,
"Unit": null
}
],
[
{
"Depth": 1,
"Type": 1,
"Unit": null
},
{
"Depth": 1,
"Type": 1,
"Unit": null
},
{
"Depth": 1,
"Type": 1,
"Unit": 2
}
]
],
"ID": "0b055e19-9b96-e492-b816-43297f12cc39"}
错误:
2014/03/28 12:11:41 http:恐慌服务127.0.0.1:56436:json:不能 将unmarshal数转换为main.Char类型的Go值。
答案 0 :(得分:1)
我制作了代码的固定版本(playground)。这似乎是一个主要的错误:
type Char struct {
ID int
HP int
CT int
Stats []int // This was statList which won't work
X int
Y int
ACList Actions
}
另请注意我对Tile
所做的定义,该定义允许数字为nil
。
type Tile struct {
Depth int
Type int
Unit *int
}
你没有提供所有的结构,所以我做了一些 - 可能是错的!总之是:
import (
"encoding/json"
"fmt"
)
type Match struct {
Teams [][]Char
Map [][]Tile
ID string //uuid
// Socket *websocket.Conn `json:'-'`
}
type Char struct {
ID int
HP int
CT int
Stats []int // This was statList which won't work
X int
Y int
ACList Actions
}
type statList struct {
Str int
Vit int
Int int
Wis int
Dex int
Spd int
}
type Action string
type Actions struct {
Actions []Action
TICKCT int
}
type Tile struct {
Depth int
Type int
Unit *int
}
var data = `{
"Teams": [
[
{
"ID": 1,
"HP": 10,
"CT": 0,
"Stats": [
1,
1,
1,
1,
1,
1
],
"X": 0,
"Y": 0,
"ACList": {
"Actions": [],
"TICKCT": 0
}
}
],
[
{
"ID": 2,
"HP": 10,
"CT": 0,
"Stats": [
1,
1,
1,
1,
1,
1
],
"X": 2,
"Y": 2,
"ACList": {
"Actions": [],
"TICKCT": 0
}
}
]
],
"Map": [
[
{
"Depth": 1,
"Type": 1,
"Unit": 1
},
{
"Depth": 1,
"Type": 1,
"Unit": null
},
{
"Depth": 1,
"Type": 1,
"Unit": null
}
],
[
{
"Depth": 1,
"Type": 1,
"Unit": null
},
{
"Depth": 1,
"Type": 1,
"Unit": null
},
{
"Depth": 1,
"Type": 1,
"Unit": null
}
],
[
{
"Depth": 1,
"Type": 1,
"Unit": null
},
{
"Depth": 1,
"Type": 1,
"Unit": null
},
{
"Depth": 1,
"Type": 1,
"Unit": 2
}
]
],
"ID": "0b055e19-9b96-e492-b816-43297f12cc39"}`
func main() {
match := new(Match)
err := json.Unmarshal([]byte(data), match)
if err != nil {
panic(err)
}
fmt.Printf("match = %#v\n", match)
}