本文转自:http://www.howtobuildsoftware.com/index.php/how-do/cg8K/jsonnet-newtonsoft-json-how-to-dynamically-change-the-date-format

I'm using Newtonsoft JSON Serializer and it's great and super fast but I'd like to do a bit more with it. I'm not sure it's possible as all the search I've done comes up to nothing. What I would like is to be able to truncate empty time, so when it's display 2014-01-01 00:00:00.000 I just want 2014-01-01 at the end, so basically cut the entire time when they're all zeros. For now I use this piece of code:

DataTable dt = loadData();

// encode the string with Newton JSON.Net
string output = JsonConvert.SerializeObject(dt,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Formatting = Newtonsoft.Json.Formatting.None,
DateFormatString = "yyyy-MM-dd HH:mm:ss"
});

Is there a way to format these dates without the time (only when they are all zeros) without affecting the performance?

Best How To :

You can do this with a custom JsonConverter:

class CustomDateConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(DateTime));
} public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
DateTime date = (DateTime)value;
string format = "yyyy-MM-dd HH:mm:ss";
if (date.Hour == 0 &&
date.Minute == 0 &&
date.Second == 0 &&
date.Millisecond == 0)
{
format = "yyyy-MM-dd";
}
writer.WriteValue(date.ToString(format));
} public override bool CanRead
{
get { return false; }
} public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

Demo:

class Program
{
static void Main(string[] args)
{
List<DateTime> dates = new List<DateTime>
{
DateTime.Now,
DateTime.Today
}; JsonSerializerSettings settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Formatting = Newtonsoft.Json.Formatting.None,
Converters = new List<JsonConverter> { new CustomDateConverter() }
}; string json = JsonConvert.SerializeObject(dates, settings); Console.WriteLine(json);
}
}

Output:

["2014-06-11 11:56:28","2014-06-11"]

[转]Newtonsoft JSON how to dynamically change the date format?的更多相关文章

  1. 调用newtonsoft.json反序列出错

    调用newtonsoft.json反序列出错: Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current J ...

  2. 找不到方法 Void Newtonsoft.Json.JsonConvert.set_DefaultSettings

    找不到方法 Void Newtonsoft.Json.JsonConvert.set_DefaultSettings 因为 Newtonsoft.Json.dll 的版本号问题: C:\Program ...

  3. Newtonsoft.Json 序列化

    当我们对一个json数组进行反序列化用Newtonsoft.Json.JsonConvert.DeserializeObject<T>() 通常会报此错误 Newtonsoft.Json. ...

  4. .Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程

    JSON作为一种轻量级的数据交换格式,简单灵活,被很多系统用来数据交互,作为一名.NET开发人员,JSON.NET无疑是最好的序列化框架,支持XML和JSON序列化,高性能,免费开源,支持LINQ查询 ...

  5. 使用Newtonsoft.Json.dll(JSON.NET)动态解析JSON、.net 的json的序列化与反序列化(一)

    在开发中,我非常喜欢动态语言和匿名对象带来的方便,JSON.NET具有动态序列化和反序列化任意JSON内容的能力,不必将它映射到具体的强类型对象,它可以处理不确定的类型(集合.字典.动态对象和匿名对象 ...

  6. Newtonsoft.Json 自定义 解析协议

    在开发web api的时候 遇到一个要把string未赋值默认为null的情况改成默认为空字符串的需求 这种情况就需要自定义json序列话的 解析协议了 Newtonsoft.Json默认的解析协议是 ...

  7. Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b9a188c8922137c6

    未能加载文件或程序集“Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b9a188c8922137c6”或它的某一个 ...

  8. Newtonsoft.Json 序列化和反序列化 时间格式【转】

    1.JSON序列化 string JsonStr= JsonConvert.SerializeObject(Entity); eg:   A a=new A(); a.Name="Elain ...

  9. Newtonsoft.Json 版本冲突解决

    在做asp.net MVC 开发时,因为引用的dll 中使用了更高版本的 Newtonsoft.Json ,导致运行时发生错误, 查资料说是因为webApi使用了Newtonsoft.Json 导致了 ...

随机推荐

  1. 小修改,让mvc的验证锦上添点花(1)

    首先,mvc的客户端验证用的是jquery.validate.js, jquery.validate本身已经提供了很好的扩展功能,通过简单点配置就可以做得更好看些. 而Microsoft通过jquer ...

  2. C# 异常日志记录

    using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Web; na ...

  3. webservice简单例子

    1.添加web服务. /// <summary> /// demo 的摘要说明 /// </summary> [WebService(Namespace = "htt ...

  4. pageadmin自助建站 网站目录权限的设置方法

    在用pageadmin网页设计的时候遇到各种问题可以参考官网教程网站目录权限的设置方法 网站目录必须设置读取和写入权限,否则后台解压,删除文件,在线上传等功能都无法正常使用,下面讲解本机和服务器配置目 ...

  5. 导出包含图片的excel、word、pdf 笔记

    /** * 导出word * @throws Exception */ @Override public byte[] WordExport( List<VbLibGlobalAnalyList ...

  6. 极大似然估计MLE 极大后验概率估计MAP

    https://www.cnblogs.com/sylvanas2012/p/5058065.html 写的贼好 http://www.cnblogs.com/washa/p/3222109.html ...

  7. 一键生成ssl自签名证书脚本

    #!/bin/bash -e # * 为必改项 # * 更换为你自己的域名 CN='' # 例如: demo.rancher.com # 扩展信任IP或域名 ## 一般ssl证书只信任域名的访问请求, ...

  8. ubuntu设置root登录ssh

    1. 默认不带ssh,所以需要安装一下ssh sudo apt install openssh-server 2 .设置root密码,ubuntu默认root密码是随机的,需要重置一下 sudo pa ...

  9. [Objective-C语言教程]数字(13)

    在Objective-C编程语言中,要以对象形式保存基本数据类型,如:int,float,bool.Objective-C提供了一系列与NSNumber一起使用的方法,一些常用重要的方法列在下表中. ...

  10. tcp 建立连接的三次握手,以及关闭连接的4次挥手

    TCP连接的三次握手 第一次握手:客户端发送syn包(syn=j)到服务器,并进入SYN_SEND状态,等待服务器确认; (客户端问服务器:你爱我吗?) 第二次握手:服务器收到syn包,必须确认客户的 ...