首页 > Go如何通用的处理请求回来的json数据?

Go如何通用的处理请求回来的json数据?

有好几个API,返回的是json格式。根据返回的JSON格式做了几个不同的struct,想写一个通用的请求方法,可以返回对应的自定义类型的变量,应该怎么做?


可以用beego框架,很多处理方案都在里面了


最简单的方法是使用 json tag,参考一下:https://github.com/douglarek/bronx/blob/master/push/lc/lc.go


可以试试这个https://github.com/bitly/go-simplejson


举个例子

type Product struct {
    ID          int             `json:"id"`
    Name        string          `json:"name"`
}

var pruduct Product

// responseBytes为http返回的字节数组
var responseBytes []Byte

//http request ...
//将请求结果的byte数组放到responseBytes中

//product就拿到了解析后的数据
json.Unmarshal(responseBytes, &pruduct)

我的做法是直接解析到map,通过key来访问值。


interface


我的做法是,api返回(interface{},error),然后自定义HttpServe,将返回值统一在这里进行处理

【热门文章】
【热门文章】