duanfan1869 2015-01-23 02:09
浏览 242
已采纳

指向JSON的指针数组

In golang I have two dimensional slice of pointers to struct, as shown in code below.

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
}

I would like to serialize cells slice into JSON. But as all the elements are pointers calling encode will give empty JSON. What would be the best way to serialize this slice.

One solution that comes to my mid is to create a local copy of this 2D slice ad replace all pointers with actual struct. It'll work but it is no

  • 写回答

1条回答 默认 最新

  • doulang5323 2015-01-23 02:35
    关注

    I'm not sure if I'm answering your question because the built in JSON package will do the reflection of the pointers automatically. It should "just work". I did notice that you are not exporting the properties in your struct, maybe that is the issue you have? When using reflection, you cannot inspect unexported values.

    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))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里