gpt4 book ai didi

json - 解码器无法解码时如何获取 JSON?

转载 作者:IT王子 更新时间:2023-10-29 01:42:10 25 4
gpt4 key购买 nike

我正在使用 json.Decoder 来解码通过网络流传输的 JSON。它工作正常,但每当有人发送不符合模式的数据时(例如,当结构的字段类型为无符号时发送负整数),它会返回一个错误,其中包含一条模糊的消息,该消息没有指出有问题的属性。这使得调试更加困难。

有没有什么方法可以提取解码器出错时试图解码的 JSON?这是一个可重现的小片段:

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 {
fmt.Println(err)
fmt.Println("TODO: how to get JSON that caused this error?")
} else {
fmt.Println(foo.Bar)
}
}

或在 Playground 上:https://play.golang.org/p/-WdYBkYEzJ

最佳答案

错误中有一些信息,类型为*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 描述。这仍然会给实现自己的解码逻辑的类型带来问题,issue 11858 引用了该逻辑。

关于json - 解码器无法解码时如何获取 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37113606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com