golang 自定义time.Time json输出格式
工作中使用golang时,遇到了一个问题。声明的struct含time.Time类型。使用json格式化struct时,time.Time被格式化成”2006-01-02T15:04:05.999999999Z07:00“格式。
代码如下
package jsontest import (
"encoding/json"
"testing"
"time"
) type Person struct {
Id int64 `json:"id"`
Name string `json:"name"`
Birthday time.Time `json:"birthday"`
} func TestTimeJson(t *testing.T) {
now := time.Now()
t.Log(now)
src := `{"id":5,"name":"xiaoming","birthday":"2016-06-30T16:09:51.692226358+08:00"}`
p := new(Person)
err := json.Unmarshal([]byte(src), p)
if err != nil {
t.Fatal(err)
}
t.Log(p)
t.Log(p.Birthday)
js, _ := json.Marshal(p)
t.Log(string(js))
}
golang的time.Time的默认json格式化格式叫做RFC3339。好像是一种国际标准,被推荐用作json时间的标准格式。但是android端不需要这种,而且不容易解析。
经过google,golang文档等途径,写了一个既能解决问题,又不会对源代码产生影响的解决方案。
先看一下google的解决方案
type Time struct {
time.Time
}
// returns time.Now() no matter what!
func (t *Time) UnmarshalJSON(b []byte) error {
// you can now parse b as thoroughly as you want
*t = Time{time.Now()}
return nil
}
type Config struct {
T Time
}
func main() {
c := Config{}
json.Unmarshal([]byte(`{"T": "bad-time"}`), &c)
fmt.Printf("%+v\n", c)
}
原文:http://stackoverflow.com/questions/25087960/json-unmarshal-time-that-isnt-in-rfc-3339-format
但是这样写会对原有的struct产生影响。在映射数据库时,就不行了。此时,心里一片乌云。。。
后来在看url包时,发现了系统包的一种声明数据类型的方式
type Values map[string][]string
根据这种声明方式,受到了启发,便写了一个自己的方法,如下
type Time time.Time const (
timeFormart = "2006-01-02 15:04:05"
) func (t *Time) UnmarshalJSON(data []byte) (err error) {
now, err := time.ParseInLocation(`"`+timeFormart+`"`, string(data), time.Local)
*t = Time(now)
return
} func (t Time) MarshalJSON() ([]byte, error) {
b := make([]byte, , len(timeFormart)+)
b = append(b, '"')
b = time.Time(t).AppendFormat(b, timeFormart)
b = append(b, '"')
return b, nil
}
同时,将Person的Birthday的类型改为Time,成功的实现的json格式化与json解析。应用到自己的项目中,不会对原有的数据库映射产生影响。需要转换类型的时候,只需Time.(xx)便可,很方便。
以为到这里便结束了。后面还有一个小坑在等我。
struct默认打印结果是将其成员完全打印出来。如把Person打印出来,便是
&{ xiaoming { 0x6854a0}}
我想要的是时间,{63602870991 0 0x6854a0} 是个什么。后来发现,自己的Time类型相当于继承了time.TIme的成员。没有像java一样继承方法。调用了struct默认打印方式。golang有没有类似于java的toString方法呢。
当然有,而且很简单
func (t Time) String() string {
return time.Time(t).Format(timeFormart)
}
这样,就实现了更改打印输出方式
&{ xiaoming -- ::}
最后,把全部代码贴出
package jsontest import (
"encoding/json"
"testing"
"time"
) type Time time.Time const (
timeFormart = "2006-01-02 15:04:05"
) func (t *Time) UnmarshalJSON(data []byte) (err error) {
now, err := time.ParseInLocation(`"`+timeFormart+`"`, string(data), time.Local)
*t = Time(now)
return
} func (t Time) MarshalJSON() ([]byte, error) {
b := make([]byte, , len(timeFormart)+)
b = append(b, '"')
b = time.Time(t).AppendFormat(b, timeFormart)
b = append(b, '"')
return b, nil
} func (t Time) String() string {
return time.Time(t).Format(timeFormart)
} type Person struct {
Id int64 `json:"id"`
Name string `json:"name"`
Birthday Time `json:"birthday"`
} func TestTimeJson(t *testing.T) {
now := Time(time.Now())
t.Log(now)
src := `{"id":,"name":"xiaoming","birthday":"2016-06-30 16:09:51"}`
p := new(Person)
err := json.Unmarshal([]byte(src), p)
if err != nil {
t.Fatal(err)
}
t.Log(p)
t.Log(time.Time(p.Birthday))
js, _ := json.Marshal(p)
t.Log(string(js))
}
由此,可以对任意struct增加 UnmarshalJSON , MarshalJSON , String 方法,实现自定义json输出格式与打印方式。
golang 自定义time.Time json输出格式的更多相关文章
- golang 自定义json解析
在实际开发中,经常会遇到需要定制json编解码的情况. 比如,按照指定的格式输出json字符串, 又比如,根据条件决定是否在最后的json字符串中显示或者不显示某些字段. 如果希望自己定义对象的编码和 ...
- golang 自定义importpath
golang 的包导入和其他语言有好多不一样的地方,以下是一个自定义的导入 golang 自定义导入说明 一个官方的说明 比较简单,就不翻译了,主要是说我们可以通过添加meta 数据告诉包如何进行加载 ...
- Loadrunner请求自定义的http(json)文件and参数化
Loadrunner请求自定义的http(json)文件and参数化 研究啦好些天这个东西啦 终于出来答案啦 嘿嘿 给大家分享一下 : 请求自定义的http文件用函数:web_custom_ ...
- springmvc 自定义view支持json和jsonp格式数据返回
1.如果controlloer上用@ResponseBody注解,则用<mvc:message-converter>里面配置的json解析器进行解析 <mvc:annotation- ...
- Json解析工具Jackson(使用注解)--jackson框架自定义的一些json解析注解
Json解析工具Jackson(使用注解)--jackson框架自定义的一些json解析注解 @JsonIgnoreProperties 此注解是类注解,作用是json序列化时将Javabean中的一 ...
- golang自定义struct字段标签
原文链接: https://sosedoff.com/2016/07/16/golang-struct-tags.html struct是golang中最常使用的变量类型之一,几乎每个地方都有使用,从 ...
- 自定义响应结构 Json格式转换 工具类
import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterx ...
- 【GoLang】golang HTTP GET/POST JSON的服务端、客户端示例,包含序列化、反序列化
服务端代码示例: package main import ( "encoding/json" "fmt" "io/ioutil" " ...
- 自定义JsonResult处理JSON序列化DateTime类型数据(Ext4.2+ASP.NET MVC 4)
最近项目中前台页面使用Extjs4.2 ,在后台ASP.NET MVC4返回的DateTime类型的数据错返回的DateTime类型的JsonResult的结果中的值是“\/Date(13784461 ...
随机推荐
- UVA 1397 - The Teacher's Side of Math(高斯消元)
UVA 1397 - The Teacher's Side of Math 题目链接 题意:给定一个x=a1/m+b1/n.求原方程组 思路:因为m*n最多20,全部最高项仅仅有20.然后能够把每一个 ...
- 常用Lunix命令
计算机 1.硬件系统 输入单元.输出单元.算术逻辑单元.控制单元.记忆单元 中央处理单元:CPU(算术逻辑单元.控制单元) 电源.主板.CPU.内存(RAM).硬盘.(声卡.显卡.网卡)(集成在主板上 ...
- robot framework运行测试 命令行启动
...\rf_test> pybot --test test_case test_suit.robot #运行一条用例 ...\rf_test> pybot test_suit.robot ...
- 实现SpringBoot登录
SpringBoot登录 https://www.cnblogs.com/jiekzou/p/9303871.html 通过前面10篇文章的学习,相信我们对SpringBoot已经有了一些了解,那么如 ...
- pgsql数据库应用两点注意
今天在写一个sql脚本时遇到了两个问题,记录一下. 1,pgsql中没有select top n语句,可以用limit n代替. 2,pgsql可以在定义函数存储过程时使用变量,但要注意函数定义中的函 ...
- [HNOI2005]星际贸易
https://www.zybuluo.com/ysner/note/1309789 题面 要素太多,还是自己看吧 解析 如果要求贸易额最大,就相当于: 有\(n\)个物品(星球),每个物品价值为\( ...
- [CF348B]Apple Tree
https://www.zybuluo.com/ysner/note/1300249 题面 给一棵大小为\(n\)的树,树的每个叶子节点上有权值. 定义一颗树平衡:对于每一个结点\(u\)的子树都拥有 ...
- ZOJ3965 Binary Tree Restoring
ZOJ3965 给定一颗二叉树的两种DFS序列 输出一种可能的二叉树的结构. 考察树的递归性质,不要想的太复杂. 当前节点在两个串中后面的节点假如不同则能确认两个子树,如果相同则把下个点作当前点的一个 ...
- 51Nod 1967 路径定向 —— 欧拉回路
题目:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1967 显然是欧拉回路问题,度数为奇数的点之间连边,跑欧拉回路就可以 ...
- nginx开发(一) 源码-编译
1:获取源码 http://nginx.org/download/nginx-1.8.0.tar.gz 2:编译 解压之后,进入根目录,执行 ./configuer.sh make make inst ...