go: Unmarshal error: json: cannot unmarshal string into Go struct field .timestamp of type int64

在我们作为Go开发工程师的工作中,错误和异常处理无疑是非常重要的一环。今天,我们来讲解一个在Go中进行JSON解析时可能会遇到的具体错误,即:ERR: Unmarshal error: json: cannot unmarshal string into Go struct field .timestamp of type int64。

背景

在进行服务端或客户端开发时,经常需要通过JSON来进行数据交换。Go标准库中的encoding/json包为我们提供了方便的JSON编解码功能。然而,类型不匹配会引发解码错误,特别是当JSON字段与Go结构字段的类型不一致时。

错误信息“json: cannot unmarshal string into Go struct field .timestamp of type int64”告诉我们,我们试图将一个字符串类型的JSON字段解析为Go结构中的一个int64类型字段,这显然是不允许的。

问题分析

首先,让我们通过一个简单的例子来复现这个问题。

type HeartBeat struct {
    Timestamp int64 `json:"timestamp"`
}
func main() {
    jsonStr := `{"timestamp": "1629894153"}`
    var hb HeartBeat
    err := json.Unmarshal([]byte(jsonStr), &hb)
    if err != nil {
        fmt.Println("ERR StartHeartBeat Unmarshal error:", err)
    }
}

运行这段代码会得到与标题中相同的错误信息。

解决方案

有几种方法可以解决这个问题。

方法1: 修改JSON数据源

如果我们对数据源有控制权,最直接的方法是确保JSON字段的类型与Go结构字段的类型匹配。

{"timestamp": 1629894153}

方法2: 使用接口类型

使用interface{}作为字段类型,然后在代码中进行类型断言。

type HeartBeat struct {
    Timestamp interface{} `json:"timestamp"`
}
var hb HeartBeat
err := json.Unmarshal([]byte(jsonStr), &hb)
timestamp, ok := hb.Timestamp.(string)
if ok {
    // 转换字符串为int64
}

方法3: 使用自定义UnmarshalJSON方法

为结构定义一个自定义的UnmarshalJSON方法。

func (h *HeartBeat) UnmarshalJSON(data []byte) error {
    var raw map[string]interface{}
    if err := json.Unmarshal(data, &raw); err != nil {
        return err
    }
    
    if ts, ok := raw["timestamp"].(string); ok {
        // 进行转换
    }
    return nil
}

总结

在我们的Go开发实践中,处理JSON解码错误是常有的事。针对json: cannot unmarshal string into Go struct field .timestamp of type int64这个错误,我们有多种解决方案,从而使我们的代码更加健壮。

这不仅增强了代码的健壮性,还为团队中的其他成员提供了解决问题的思路,是我们迈向软件架构师的一小步。

如果您对这篇文章有任何疑问或建议,欢迎在下面留言。同时,如果你对企业管理,团队管理,项目管理或个人成长有兴趣,也请关注我的其他文章。