由于前台web页面传来的日期对象是这样的格式“2010-11-03 15:23:22”,所以我安装网上查来的办法,自定义包装了time.Time对象,实现自己的Marshal和UnMarshal方法

type DateTime struct {
time.Time
} const ctLayout = "2006-01-02 15:04:05"
const ctLayout_nosec = "2006-01-02 15:04"
const ctLayout_date = "2006-01-02" func (this *DateTime) UnmarshalJSON(b []byte) (err error) { if b[0] == '"' && b[len(b)-1] == '"' {
b = b[1 : len(b)-1]
}
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
panic(err)
}
sv := string(b)
if len(sv) == 10 {
sv += " 00:00:00"
} else if len(sv) == 16 {
sv += ":00"
}
this.Time, err = time.ParseInLocation(ctLayout, string(b), loc)
if err != nil {
if this.Time, err = time.ParseInLocation(ctLayout_nosec, string(b), loc); err != nil {
this.Time, err = time.ParseInLocation(ctLayout_date, string(b), loc)
}
} return
} func (this *DateTime) MarshalJSON() ([]byte, error) { rs := []byte(this.Time.Format(ctLayout)) return rs, nil
} var nilTime = (time.Time{}).UnixNano() func (this *DateTime) IsSet() bool {
return this.UnixNano() != nilTime
}

然后,把结构中声明为time.Time的都修改为自定义的类型DateTime,试了一下,发现已经可以正确解析网页发来的时间,但是在输出时,总是不对,好像并没有调用自定义的Marshal方法。编写测试方法发现,原来json.Marshal方法调用DateTime.Marshal时出错了!

 invalid character '-' after top-level value 

开始没有认真看,以为“-”号不合法,就换了一个,结果错误一样:

 invalid character '/' after top-level value 

看来,根本不是分割符的问题,仔细分析错误,发现“top-level”字样,我这返回的就是一个字符串,怎么可能top-level呢!想到这儿突然醒悟,是不是返回字符串应该自己加引号呢,急忙修改代码一试,果然!~_~

最终代码如下:

type DateTime struct {
time.Time
} const ctLayout = "2006-01-02 15:04:05"
const ctLayout_nosec = "2006-01-02 15:04"
const ctLayout_date = "2006-01-02" func (this *DateTime) UnmarshalJSON(b []byte) (err error) { if b[0] == '"' && b[len(b)-1] == '"' {
b = b[1 : len(b)-1]
}
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
panic(err)
}
sv := string(b)
if len(sv) == 10 {
sv += " 00:00:00"
} else if len(sv) == 16 {
sv += ":00"
}
this.Time, err = time.ParseInLocation(ctLayout, string(b), loc)
if err != nil {
if this.Time, err = time.ParseInLocation(ctLayout_nosec, string(b), loc); err != nil {
this.Time, err = time.ParseInLocation(ctLayout_date, string(b), loc)
}
} return
} func (this *DateTime) MarshalJSON() ([]byte, error) { rs := []byte(fmt.Sprintf(`"%s"`, this.Time.Format(ctLayout))) return rs, nil
} var nilTime = (time.Time{}).UnixNano() func (this *DateTime) IsSet() bool {
return this.UnixNano() != nilTime
}

【玩转Golang】 自定义json序列化对象时,非法字符错误原因的更多相关文章

  1. EF中Json序列化对象时检测到循环引用的解决办法

    MVC4 EF中将数据表外键引用的是自身,转换成Json时,总是提示错误:“序列化类型为....的对象时检测到循环引用.”: 解决办法: 把要序列化的对象转为匿名对象去掉导航属性,如下 :本来是var ...

  2. 使用DataContractJsonSerializer发序列化对象时出现的异常

    最近服务器上的某个程序的错误日志中频繁出现以下异常: Deserialising: There was an error deserializing the object of type {type} ...

  3. .NET 自定义Json序列化时间格式

    .NET 自定义Json序列化时间格式 Intro 和 JAVA 项目组对接,他们的接口返回的数据是一个json字符串,里面的时间有的是Unix时间戳,有的是string类型,有的还是空,默认序列化规 ...

  4. JSON.Net 自定义Json序列化时间格式

    JSON.Net 自定义Json序列化时间格式 Intro 和 JAVA 项目组对接,他们的接口返回的数据是一个json字符串,里面的时间有的是Unix时间戳,有的是string类型,有的还是空,默认 ...

  5. Error serializing object:序列化对象时出错

    序列化对象时出错 :Error serializing object. Error serializing object. Cause: java.io.NotSerializableExceptio ...

  6. 【翻译自mos文章】使用aum( Automatic Undo Management) 时遇到 ORA-01555错误--- 原因和解决方式。

    使用aum( Automatic Undo Management) 时遇到 ORA-01555错误--- 原因和解决方式. 參考原文: ORA-01555 Using Automatic Undo M ...

  7. SpringBoot之解决一对一、多对一、多对多等关联实体在JSON序列化/输出时产生的无限递归死循环问题(infinite recursion)

    前言 这问题着实让人苦不堪言,有必要把它记下了. @JsonBackReference [亲测有效] 1.使用注解@JsonBackReference标记在有关联关系的实体属性上 2.仅导入此注解类有 ...

  8. Json序列化对象

    之前都是用的二进制的序列化方法,是.net自带的,但是最常用到的还是Json序列化 (1)只需要调用 Newtonsoft.Json.dll 即可 public class JsonTools { / ...

  9. Gson序列化对象时排除字段

    import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; /** *Gson序列化对象排除属性 ...

随机推荐

  1. Vim中的寄存器

    # Vim中的寄存器 ### 文件名寄存器---- 粘贴文件名 `"%p"` ### 查看vim中的寄存器---- 查看寄存器 `reg` 或 `dis` ### 详细介绍---- ...

  2. in linux system of ftp command

    一口流利的english title 常用命令: ftp baidu.com ftp>ls ftp>cd directory ftp>get filename 下载 ftp>p ...

  3. Python的自增运算符

    今天在写一个合并两个有血list的时候,使用了while循环,不自觉的使用了i++,自测的时候发现有语法错误,还检查了好几遍,觉得应该没啥错误啊,后来google了一把,恍然大悟,原来Python早就 ...

  4. Linux 下编译出现 undefined reference to `pthread_create'

    这是由于没有链接线程库的原因,只要在编译的时候加入: -lpthread 参数即可. arm-linux-gcc serial.c -o serial -lpthread 查看 ubuntu 版本的命 ...

  5. Linxu

    http://www.92csz.com/study/linux/ MySql 乱码  修改 /etc/my.cnf文件 character-set-server=utf8 , 表名不区分大小写:lo ...

  6. 人工智能常用 API

    人工智能常用 API 转载  2016年07月13日 19:17:27 2047 机器学习与预测 1.AlchemyAPI  在把数据由非结构化向结构化的转化中运用得较多.用于社交媒体监控.商业智能. ...

  7. react学习资源

    http://www.ruanyifeng.com/blog/2015/03/react.html http://www.ruanyifeng.com/blog/2015/02/future-of-d ...

  8. CentOS防SYN攻击

    netstat -anp |awk '{print $6}'|sort|uniq -c |sort -rn 172 ESTABLISHED 59 CONNECTED 589 SYN_RECV 15 S ...

  9. golang sqrt error练习

      练习:错误 从先前的练习中复制 Sqrt 函数,并修改使其返回 error 值. 由于不支持复数,当 Sqrt 接收到一个负数时,应当返回一个非 nil 的错误值. 创建一个新类型 type Er ...

  10. VS2017安装PCL1.8.1

    很多使用在windows环境下编译和使用PCL,这样让我想试试,所以就迫不得已的放弃使用Ubuntu环境,但是我还是建议使用Ubuntu系统,毕竟在Ubuntu下几条命令就搞定了,为了迎合在windo ...