去:什么时候会json.Unmarshal结构返回错误? [英] Go : When will json.Unmarshal to struct return error?

查看:333
本文介绍了去:什么时候会json.Unmarshal结构返回错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个像

 类型的结构体struct {
name string`json:name
}

然后在主要代码中

  var jsonString string =`{status:false}`
var a A
错误:= json.Unmarshal([] byte(jsonString ),& a)

显然上面的代码产生了一个零错误,无论json格式是不同的。什么时候json.Unmarshal()在Go中返回错误?

解决方案

不符合目标中的值。例如,如果源包含字段status,但目标没有,则不是错误。



Unmarshal函数在其他情况下确实返回错误:



语法错误

  type A struct {
名称字符串` json:name`
}
data = [] byte(`{name:what?}`)
err = json.Unmarshal(data,& a)
fmt.Println(err)//打印字符'w'寻找值的开始

失配

  data:= [] byte(`{name:false}`)
type B struct {
名称字符串`json:name`
}
var b B
err = json.Unmarshal(data,& b)
fmt.Println(err )//打印不能将bool转换为字符串类型的Go值

游乐场示例


Assume i have a struct like

type A struct{
  name string`json:"name"`
}

Then in main i have code

var jsonString string = `{"status":false}`
var a A
error := json.Unmarshal([]byte(jsonString),&a)

apparently the code above produce a nil error, regardless the json format is different. When will json.Unmarshal() return error in Go?

解决方案

The JSON decoder does not report an error if values in the source do not correspond to values in the target. For example, it's not an error if the source contains the field "status", but the target does not.

The Unmarshal function does return errors in other situations:

Syntax error

type A struct {
    Name string `json:"name"`
}
data = []byte(`{"name":what?}`)
err = json.Unmarshal(data, &a)
fmt.Println(err)  // prints character 'w' looking for beginning of value

Type Mismatch

data := []byte(`{"name":false}`)
type B struct {
  Name string `json:"name"`
}
var b B
err = json.Unmarshal(data, &b)
fmt.Println(err) // prints cannot unmarshal bool into Go value of type string

playground example

这篇关于去:什么时候会json.Unmarshal结构返回错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆