dqwh1205 2016-01-26 08:17
浏览 363

Golang UnmarshalTypeError缺少偏移

I'm totally newbie in Golang and solving problem with parsing JSON. Everything is working, except error handling.

if err := json.Unmarshal(file, &configData); err != nil {    
    if ute, ok := err.(*json.UnmarshalTypeError); ok {
        fmt.Printf("UnmarshalTypeError %v - %v - %v", ute.Value, ute.Type, ute.Offset)        
    }
}

Here I get error ute.Offset undefined (type *json.UnmarshalTypeError has no field or method Offset) but in Docs of JSON package and also code they have this variable in UnmarshalTypeError struct.

What I'm doing wrong? Thank you

  • 写回答

1条回答 默认 最新

  • dongshuxi3105 2016-01-26 09:18
    关注

    According to the godoc description:

    If a JSON value is not appropriate for a given target type, or if a JSON number overflows the target type, Unmarshal skips that field and completes the unmarshalling as best it can. If no more serious errors are encountered, Unmarshal returns an UnmarshalTypeError describing the earliest such error.

    Just like string type unmarshals into chan type,it make a UnmarshalTypeError error,just like the following:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type A struct {
        Name string
        Chan chan int
    }
    
    func main() {
        var a A
        bs := []byte(`{"Name":"hello","Chan":"chan"}`)
        if e := json.Unmarshal(bs, &a); e != nil {
            if ute, ok := e.(*json.UnmarshalTypeError); ok {
                fmt.Printf("UnmarshalTypeError %v - %v - %v
    ", ute.Value, ute.Type, ute.Offset)
            } else {
                fmt.Println("Other error:", e)
            }
        }
    }
    

    Outputs:

    UnmarshalTypeError string - chan int - 29
    

    It is working properly!

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大