情况1 返回的json是string,struct里边的tag是其他类型比如是int.则报错

返回的json如下 :

{"loan_product_id":"101","manage_rate":"0.41","overdue_rate":"0.09","late_fee_rate":"0.00"}

go -Unmarshal 错误的几种情况_字符串

go -Unmarshal 错误的几种情况_string类_02

type OrderRet struct {
ProductId int `json:"loan_product_id,int"`
OverdueRate float64 `json:"overdue_rate,string"` //
MangeRate float64 `json:"manage_rate,string"`
LateFeeRate float64 `json:"late_fee_rate,string"`
}

比如 OrderRet 结构体里边的 ProductId 类型是int, tag是int 但是json返回是string类型。报错为

cannot unmarshal string into Go struct field OrderRet.loan_product_id of type int

go -Unmarshal 错误的几种情况_golang_03

情况2 返回的json是int,struct里边的tag是其他类型比如是string.则报错

返回的josn

{"loan_product_id":101,"manage_rate":"0.41","overdue_rate":"0.09","late_fee_rate":"0.00"}

go -Unmarshal 错误的几种情况_string类_04

type OrderRet struct {
ProductId int `json:"loan_product_id,string"`
OverdueRate float64 `json:"overdue_rate,string"` //
MangeRate float64 `json:"manage_rate,string"`
LateFeeRate float64 `json:"late_fee_rate,string"`
}
或者结构体
type OrderRet struct {
ProductId string `json:"loan_product_id,string"`
OverdueRate float64 `json:"overdue_rate,string"` //
MangeRate float64 `json:"manage_rate,string"`
LateFeeRate float64 `json:"late_fee_rate,string"`
}
ProductId string `json:"loan_product_id,string"` 类型是 int或者 string,但是tag的与json的int不一样,这里的tag是string

比如 OrderRet 结构体里边的 ProductId 类型是int, tag是string 但是json返回是int类型。报错为

invalid use of ,string struct tag, trying to unmarshal unquoted value into string

go -Unmarshal 错误的几种情况_json_05

正常情况 返回的json是字符串,struct是string,tag是int类型,这种不报错

go -Unmarshal 错误的几种情况_golang_06