2016-01-26 43 views
1

我是Golang的新手,解決了解析JSON的問題。一切正常,除了錯誤處理。Golang UnmarshalTypeError missing Offset

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)   
    } 
} 

在這裏,我得到錯誤ute.Offset undefined (type *json.UnmarshalTypeError has no field or method Offset)但在Docs of JSON packagecode他們在UnmarshalTypeError結構這個變量。

我在做什麼錯了?謝謝

+1

您使用的是哪個版本的Go? – kostya

+1

在Go 1.5中添加了'UnmarshalTypeError.Offset':https://github.com/golang/go/blob/master/api/go1.5.txt#L286 – kostya

+0

這就是問題所在。我有1.2.1,但不知道爲什麼。安裝在Ubuntu14.04上,apt-get就在昨天.. – Arxeiss

回答

1

按照godoc描述:

如果JSON值是不適合給定的目標類型,或者如果JSON溢出次數的目標類型,解組跳過該領域並完成解組爲最好的可以。如果沒有遇到更嚴重的錯誤,Unmarshal將返回一個描述最早此類錯誤的UnmarshalTypeError。

就像string型解組到chan類型,它使一個UnmarshalTypeError錯誤,就像下面:

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\n", ute.Value, ute.Type, ute.Offset) 
     } else { 
      fmt.Println("Other error:", e) 
     } 
    } 
} 

輸出:

UnmarshalTypeError string - chan int - 29 

它工作正常!

+0

問題是在我的情況下舊版本的Golang ..檢查我的帖子下的評論 – Arxeiss