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 pointnet2包安装
  • ¥20 射频功率问题,解答者有酬谢!
  • ¥80 构建降雨和积水的预测模型
  • ¥15 #Qt Transform setTransform()在鼠标拖动移动视角是一致在原地不动,无法变换视角(细微观察似乎视图有在原地抖动),无法变换视角(细微观察似乎视图有在原地抖动)
  • ¥50 如何利用无人机拍摄的数码照片测量鸟卵的长短径
  • ¥100 github贡献者给与奖励
  • ¥15 使用DS18B20+ESP8266获取温度数据返回-127.00
  • ¥15 odbc代码新增sqlserver数据源
  • ¥15 求一个USB指纹识别的驱动
  • ¥15 wps中工作表与工作表之间怎么汇总信息?