本文转自: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. orcal exists

    Oracle使用了一个复杂的自平衡B-tree结构.通常,通过索引查询数据比全表扫描要快.当 Oracle找出执行查询和Update语句的最好路径时,Oracle优化器将使用索引.同样在联结多个表时使 ...

  2. “全栈2019”Java第三十五章:面向对象

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...

  3. 51nod1847 奇怪的数学题 (Min_25筛+第二类斯特林数)

    link \(\sum_{i=1}^n\sum_{j=1}^n\mathrm{sgcd}(i,j)^k=\sum_{p=1}^ns(p)^k\sum_{i=1}^n\sum_{j=1}^n[\gcd( ...

  4. __getitem__

    如果在类中定义了__getitem__()方法,那么他的实例对象(假设为P)就可以这样P[key]取值.当实例对象做P[key]运算时,就会调用类中的__getitem__()方法.

  5. Kettle 值映射

    在费用转换里面做了两个值映射.一个是编码.一个是名称.其中两个值映射设置不一样效果不一样. 第一个编码映射 目标字段名不为空,则表示会新增字段.其中复核源值条件的都会转换为目标值,不符合条件的会用[不 ...

  6. mysql 存储过程和游标

    CREATE DEFINER=`root`@`localhost` PROCEDURE `NewProc`() BEGIN #Routine body goes here... DECLARE ite ...

  7. lua小试牛刀

    function function max(num1, num2) if(num1 > num2) then result = num1; else result = num2; end ret ...

  8. HTML5 Canvas核心技术 图形、动画与游戏开发学习总结

    save 和 restore 函数的应用 保存canvas和恢复canvas clip函数的应用 文字的绘制 背景图片的绘制 离屏canvas 基于时间的运动

  9. 初识express

    初识Express 1.简介: express是基于Nodejs平台的快速,开放,极简的web开发框架 2.安装 npm install express --save 3.Hello world: c ...

  10. rest-assured之如何指定请求数据(Specifying Request Data 包括请求参数、请求头、cookie等)

    我们除了可以为一个请求指定请求参数之外,还可以指定请求头(header).cookies.请求体(body)以及请求内容类型(content-type)等,下面我们就来一一介绍一下: 一.请求HTTP ...