drb56625 2016-10-07 09:54
浏览 101
已采纳

Golang Unmarshal JSON

My input JSON, has a list of different elements.
I have problems with the number of the first element of response.

Simplified example:

package main

import (
    "fmt"
    "log"
    "encoding/json"
)

var j = ` {
  "response": [
    777, // problem here !!!
    {
      "id": 888,
      "from_id": 999,
      "to_id": 888,
      "text": "hello..."
    },
        {
      "id": 999,
      "from_id": 888,
      "to_id": 999,
            "text": "goodbye..."
    }
  ]
}`

type D struct {
    Id     int `json:"id"`
    FromId int `json:"from_id"`
    ToId   int `json:"to_id"`
    Text   string `json:"text"`
}

type R struct {
    Count    int
    Response []D `json:"response"`
}

func main() {
    var data = new(R)
    err := json.Unmarshal([]byte(j), &data)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(data.Response)
}

Error on output. I do not understand where the error. Help me please.


  • 写回答

3条回答 默认 最新

  • duanhunlou7051 2016-10-07 10:50
    关注

    1- Here is the working code,try it on The Go Playground:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func main() {
        var d *R
        err := json.Unmarshal([]byte(str), &d)
        if err != nil {
            panic(err)
        }
        var data R2
        data.Count = int(d.Response[0].(float64))
    
        for _, v := range d.Response[1:] {    
            bs, err := json.Marshal(v)
            if err != nil {
                panic(err)
            }
            var d1 *D
            err = json.Unmarshal(bs, &d1)
            if err != nil {
                panic(err)
            }
            data.Response = append(data.Response, *d1)
        }
        fmt.Println(data)    
    }
    
    type R struct {
        Response []interface{} `json:"response"`
    }
    
    var str = ` {
      "response": [
        777,  
        {
          "id": 888,
          "from_id": 999,
          "to_id": 888,
          "text": "hello"
        },
            {
          "id": 999,
          "from_id": 888,
          "to_id": 999,
                "text": "goodbye"
        }
      ]
    }`
    
    type D struct {
        Id     int    `json:"id"`
        FromId int    `json:"from_id"`
        ToId   int    `json:"to_id"`
        Text   string `json:"text"`
    }
    type R2 struct {
        Count    int
        Response []D
    }
    

    output:

    {777 [{888 999 888 hello} {999 888 999 goodbye}]}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?