3 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個贊
錯誤中有一些信息,它是類型 *json.UnamrshalTypeError
type UnmarshalTypeError struct {
Value string // description of JSON value - "bool", "array", "number -5"
Type reflect.Type // type of Go value it could not be assigned to
Offset int64 // error occurred after reading Offset bytes
}
您可以獲取 json 字符串中的偏移量、reflect.Type被解組到的字段的偏移量以及 Value 的 json 描述。這仍然會給實(shí)現(xiàn)自己的解組邏輯的類型帶來問題,問題 11858引用了該邏輯

TA貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個贊
從 Go 1.8 開始,這現(xiàn)在是可能的。該UnmarshalTypeError類型現(xiàn)在包含Struct和Field值,這些值提供了導(dǎo)致類型不匹配的結(jié)構(gòu)和字段的名稱。
package main
import (
"bytes"
"fmt"
"encoding/json"
)
func main() {
buff := bytes.NewBufferString("{\"bar\": -123}")
decoder := json.NewDecoder(buff)
var foo struct{
Bar uint32
}
if err := decoder.Decode(&foo); err != nil {
if terr, ok := err.(*json.UnmarshalTypeError); ok {
fmt.Printf("Failed to unmarshal field %s \n", terr.Field)
} else {
fmt.Println(err)
}
} else {
fmt.Println(foo.Bar)
}
}
錯誤消息字符串也已更改為包含此新信息。
去 1.8:
json: cannot unmarshal number -123 into Go struct field .Bar of type uint32
轉(zhuǎn)到 1.7 及更早版本:
json: cannot unmarshal number -123 into Go value of type uint32

TA貢獻(xiàn)1854條經(jīng)驗(yàn) 獲得超8個贊
您可以decode.Token()在Playground和以下(根據(jù)您的示例修改)中使用這樣的方法獲取每個元素、鍵、值甚至分隔符:
package main
import (
"bytes"
"encoding/json"
"fmt"
)
func main() {
buff := bytes.NewBufferString(`{"foo": 123, "bar": -123, "baz": "123"}`)
decoder := json.NewDecoder(buff)
for {
t, err := decoder.Token()
if _, ok := t.(json.Delim); ok {
continue
}
fmt.Printf("type:%11T | value:%5v //", t, t)
switch t.(type) {
case uint32:
fmt.Println("you don't see any uints")
case int:
fmt.Println("you don't see any ints")
case string:
fmt.Println("handle strings as you will")
case float64:
fmt.Println("handle numbers as you will")
}
if !decoder.More() {
break
}
if err != nil {
fmt.Println(err)
}
}
}
這將輸出
type: string | value: foo //handle strings as you will
type: float64 | value: 123 //handle numbers as you will
type: string | value: bar //handle strings as you will
type: float64 | value: -123 //handle numbers as you will
type: string | value: baz //handle strings as you will
type: string | value: 123 //handle strings as you will
您可以根據(jù)需要打開類型并處理每個類型。我也展示了一個簡單的例子,結(jié)果中的每個“//comments”都是基于類型的條件。
您還會注意到每個數(shù)字的類型都是 float64,盡管它們適合 int,或者在“foo”值的情況下甚至是 uint,我在 switch 中檢查了這些類型,但它們從未被使用過。您必須提供自己的邏輯,以便將 float64 值轉(zhuǎn)換為您想要的類型(如果可能)并處理不會轉(zhuǎn)換為特殊情況、錯誤或任何您想要的類型。
- 3 回答
- 0 關(guān)注
- 218 瀏覽
添加回答
舉報