指向 JSON 的指针数组

Array of pointers to JSON

在 golang 中,我有指向结构的二维指针切片,如下面的代码所示。

type point struct {
    x int
    y int
}

type cell struct {
    point   point
    visited bool
    walls   walls
}

type walls struct {
    n bool
    e bool
    s bool
    w bool
}

type maze struct {
    cells         [][]*cell
    solutionStack Stack
}

我想将单元格切片序列化为 JSON。但是由于所有元素都是指针,因此调用 encode 将给出空 JSON。序列化此切片的最佳方法是什么。

我想到的一个解决方案是创建此 2D 切片的本地副本,并将所有指针替换为实际结构。它会起作用,但它不是

我不确定我是否在回答你的问题,因为内置的 JSON 包会自动进行指针的反射。它应该 "just work"。我确实注意到您没有导出结构中的属性,也许这就是您遇到的问题?使用反射时,您无法检查未导出的值。

http://play.golang.org/p/zTuMLBgGWk

package main

import (
    "encoding/json"
    "fmt"
)

type point struct {
    X int
    Y int
}

type cell struct {
    Point   point
    Visited bool
    Walls   walls
}

type walls struct {
    N bool
    E bool
    S bool
    W bool
}

type maze struct {
    Cells [][]*cell
}

func main() {
    m := maze{}

    var row1 []*cell
    var row2 []*cell

    row1 = append(row1, &cell{
        Point: point{1, 2},
        Walls: walls{N: true},
    })
    row2 = append(row2, &cell{
        Point: point{3, 4},
        Walls: walls{E: true},
    })
    m.Cells = append(m.Cells, row1, row2)

    mazeJson, _ := json.MarshalIndent(m, "", "  ")
    fmt.Println(string(mazeJson))
}