json - 指向 JSON 的指针数组

标签 json pointers go

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

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
}

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

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

最佳答案

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

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))
}

关于json - 指向 JSON 的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28101966/

相关文章:

string - 具有 PWideChar 参数的函数仅采用第一个字符

pointers - Kotlin 有指针吗?

javascript - JSON to Go结构

function - 在 Go 条件模板中使用自定义函数

JavaScript JSON 组合和数据 Anylish

c++ - 在 C++ 中 decltype 取消引用的指针

python - 在字典列表中查找键值,然后替换其他值

c - 如何将 C.AVFrame* 转换为 image.Image?

json - postgresql json - 搜索数组是否包含元素

android - 在 android 中制作 toast 时出现异常