我有结构体
type tySurvey struct {
Id int64 `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}我做json.Marshal写JSON字节在超文本标记语言页面。jQuery修改object中的name字段,并使用jQueries JSON.stringify对object进行编码,jQuery将字符串发布到Go处理程序。
编码为字符串的id字段。
已发送:已接收{"id":1}:{"id":"1"}
问题是,因为id不再是整数,所以json.Unmarshal无法解组该JSON。
json: cannot unmarshal string into Go value of type int64处理这些数据的最佳方式是什么?我不希望手动转换每个字段。我希望写紧凑,无bug的代码。
Quotes还不算太差。JavaScript不能很好地与int64配合使用。
我想学习用int64值中的字符串值对json进行解组的简单方法。
发布于 2014-01-16 10:55:58
这是通过将,string添加到您的标记来处理的,如下所示:
type tySurvey struct {
Id int64 `json:"id,string,omitempty"`
Name string `json:"name,omitempty"`
}这可以在Marshal的文档中找到。
请注意,您不能通过指定omitempty来解码空字符串,因为它只在编码时使用。
发布于 2020-09-24 18:16:07
使用json.Number
type tySurvey struct {
Id json.Number `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}发布于 2021-04-25 15:46:45
您还可以为int或int64创建一个类型别名,并创建一个自定义的json解组程序示例代码:
// StringInt create a type alias for type int
type StringInt int
// UnmarshalJSON create a custom unmarshal for the StringInt
/// this helps us check the type of our value before unmarshalling it
func (st *StringInt) UnmarshalJSON(b []byte) error {
//convert the bytes into an interface
//this will help us check the type of our value
//if it is a string that can be converted into a int we convert it
///otherwise we return an error
var item interface{}
if err := json.Unmarshal(b, &item); err != nil {
return err
}
switch v := item.(type) {
case int:
*st = StringInt(v)
case float64:
*st = StringInt(int(v))
case string:
///here convert the string into
///an integer
i, err := strconv.Atoi(v)
if err != nil {
///the string might not be of integer type
///so return an error
return err
}
*st = StringInt(i)
}
return nil
}
func main() {
type Item struct {
Name string `json:"name"`
ItemId StringInt `json:"item_id"`
}
jsonData := []byte(`{"name":"item 1","item_id":"30"}`)
var item Item
err := json.Unmarshal(jsonData, &item)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", item)
}https://stackoverflow.com/questions/21151765
复制相似问题