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 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程