dongpaipu8394 2016-09-21 15:17
浏览 109
已采纳

Golang:json Unmarshal无法解压缩简单示例

I cannot get my head around this problem. I have a simple struct, and another struct that uses it twice:

type Range struct {
    Position int `json:"position"`
    Length   int `json:"length"`
}

type TwoRanges struct {
    From Range `json:"from"`
    To   Range `json:"to"`
}

and the following json sample in file "ranges.json":

{
"from:": {
    "position": 348,
    "length": 15
},
"to": {
    "position": 737,
    "length" : 10
}
}

I try unmarshalling the sample in the following code:

func main() {
    buffer, err := ioutil.ReadFile("ranges.json")
    if err != nil {
        log.Fatal(err)
    }
    var sample TwoRanges
    if err = json.Unmarshal(buffer, &sample); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%v
", sample)
}

The output is

{{0 0} {737 10}}

Somehow, only the half of the struct is unpacked.

  1. Is it a bug, or am I doing something wrong?
  2. Is there a "verbose mode" for the encoding/json package which would tell me what went wrong with the unmarshaller? It's not the first time that I've had mysterious problems with that package.
  • 写回答

2条回答 默认 最新

  • dongya1875 2016-09-21 15:34
    关注

    note that:

    the "from:" should be "from" in your ranges.json

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入