本文转自: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. mysql 命令备份还原

    备份 mysqldump -h localhost -uroot -p123456 springbootdb > e:/springbootdb.sql 还原 mysql -h localhos ...

  2. 【05】循序渐进学 docker:系统资源和网络

    写在前面的话 在上一篇学习 Dockerfile 的时候其实还有几个相当重要得关键中没有谈到,但没关系,在后面的内容会单独提出来一个一个的学习.这里就先谈谈关于资源的控制个容器的网络~ 资源限制 其实 ...

  3. 279. 完全平方数 leetcode JAVA

    题目: 给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n.你需要让组成和的完全平方数的个数最少. 示例 1: 输入: n = 12 输出: 3 解释: ...

  4. GPU大百科全书 第一章:美女 方程与几何

    沉鱼落雁   前言:当你酣战在星际2的时候,或者当你在艾泽拉斯游历的时候,你有没有想过,眼前的这些绚丽的画面究竟是怎么来的呢?也许对大多数人来说,GPU对于图形的处理过程并不是那么重要,但总会有些人, ...

  5. OCP 052最新考试题库和答案收集-34

    34.Which two can be backed up by using RMAN when a database Is open in ARCHIVELOG mode, so that medi ...

  6. 将yum源更换为阿里的源(脚本)

    #!/bin/bash ######################################### #Function: update source #Usage: bash update_s ...

  7. 洛谷P4548 [CTSC2006]歌唱王国(概率生成函数)

    题面 传送门 给定一个长度为\(L\)的序列\(A\).然后每次掷一个标有\(1\)到\(m\)的公平骰子并将其上的数字加入到初始为空的序列\(B\)的末尾,如果序列B中已经出现了给定序列\(A\), ...

  8. Linux 下 SSH 远程超时解决方案

    Linux 下 SSH 远程超时解决方案 今天突然看到一个问题说是如何解决SSH远程超时的问题. 找了一点资料.用于解决这个需求~ 第一种:OpenSSH 配置文件设置 位于112行的 "C ...

  9. 一款不错的jQuery分页插件--pagination

    一.前言: 分页功能在项目中时常用到,一款可以快速实现分页功能的插件非常有必要,pagination--这款插件功能非常完美,几乎我所有项目中使用到分页的地方都会第一时间考虑到这个插件,但是其实有能力 ...

  10. 在Mondrian Virtual OLAP Cube中观察星座模型多事实表度量值的聚合

    这样设置的Schema文件会怎么样呢?用Saiku预览一下. 如果这时候想同时引用两个项目进行计算就会出问题了.那么这种情况怎么解决? 参考网上一段实现思路 <VirtualCube name= ...