dsue14118 2016-12-03 17:01
浏览 970
已采纳

Go:JSON输入和JSON意外结束.Unmarshal返回nil值

I'm testing out how to unmarshal a json response from an API I'm using.

The json looks something like the following;

body := []byte(`[
    {"name":"Name1", "value":100.00},
    {"name":"Name2", "value":200.00}
]`)

I've searched around for various ways to do this, but fail to get this to work. The unmarshal returns zero values. I also get an error "unexpected end of JSON input" (I've removed the error handling in the example).

Full code example - https://play.golang.org/p/VMdWuAm6HS

Reference:

  1. https://godoc.org/encoding/json#RawMessage
  2. Golang json Unmarshal "unexpected end of JSON input"
  3. How to unmarshal json into interface{} in golang?
  • 写回答

1条回答 默认 最新

  • drbae3964 2016-12-03 17:17
    关注

    Your input JSON can be modeled with a simple []Obj where Obj is your type:

    type Obj struct {
        Name  string  `json:"name"`
        Value float32 `json:"value"`
    }
    

    Nothing else is required, really:

    body := []byte(`[
        {"name":"Name1", "value":100.00},
        {"name":"Name2", "value":200.00}]`)
    
    var res []Obj
    err := json.Unmarshal(body, &res)
    fmt.Printf("%#v
    %v
    ", res, err)
    

    Output contains the data from the input JSON (try it on the Go Playground):

    []main.Obj{main.Obj{Name:"Name1", Value:100}, main.Obj{Name:"Name2", Value:200}}
    <nil>
    

    Back to your code:

    Where you're going wrong is that you use this model:

    type Obj struct {
        Name string `json:"name"`
        Value float32 `json:"value"`
    }
    
    type Result struct {
        Data json.RawMessage
    }
    
    var res []Result
    

    But this res variable would model the following JSON:

    [
        {"Data":{"name":"Name1", "value":100.00}},
        {"Data":{"name":"Name2", "value":200.00}}
    ]
    

    I think you can see the difference: the elements of the array here are JSON Objects with a "Data" field, which then are modeled with your Obj. This input JSON is then properly parsed with your original parsing code, you can try it on the Go Playground:

    [{{"name":"Name1", "value":100.00}} {{"name":"Name2", "value":200.00}}] 
    &main.Obj{Name:"Name1", Value:100} 
    &main.Obj{Name:"Name2", Value:200}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘