dsjhejw3232 2018-05-05 11:13
浏览 52
已采纳

解组数组中的单个元素

Is there a way to unmarshall JSON arrays into single objects in Go?

I have a json response from an endpoint:

{
  "results": [
    {
        "key": "value"
    }
  ]
}

I have a Go struct for the object inside the array:

type Object struct {
    Key string `json:"key"`
}

...and a struct for the response object:

type Response struct {
    Objects []Object `json:"results"`
}

results is an array of objects, but I know that the endpoint will only ever return an array with 1 object. Is there a way to unmarshall the data and avoid having reference the object by an index? I was hoping I could use something like json:"results[0]" as a field tag.

I'd prefer to be able to:

decoder.Decode(&response)
response.Object.Key

Rather than

decoder.Decode(&response)
response.Objects[0].Key
  • 写回答

2条回答 默认 最新

  • duan4739 2018-05-05 12:02
    关注

    To does this you need to customize unmarshalling. An way is create a ResponseCustom like:

    //Response json (customized) that match with Unmarshaler interface
    type ResponseCustom struct {
        Object
    }
    
    func (r *ResponseCustom) UnmarshalJSON(b []byte) error{
        rsp := &Response{}
        err := json.Unmarshal(b, rsp)
        if err != nil {
            log.Fatalln("error:", err)
        } else {
            r.Object = rsp.Objects[0]
        }
        //
        return err
    }
    

    So you can use ResponseCustom instead of you Response for get Object value. Look:

    func main() {
        //
        data := []byte(jsondata)
        resp := &ResponseCustom{}
        //
        json.Unmarshal(data, resp)
        //
        fmt.Println("My Object.value is: " + resp.Object.Key)
    }
    

    The result is:

        My Object.value is: value
    

    In playground: https://play.golang.org/p/zo7wOSacA4w

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

报告相同问题?

悬赏问题

  • ¥15 如何在sql server里完成筛选
  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了