JSON使用DateFormatHandling 序列化与反序列化日期设置

本文详细介绍了如何使用JSON.NET进行日期的序列化与反序列化操作,包括JSON日期格式化处理、使用DateFormatHandling和DateFormatString设置日期格式、以及序列化日期列表的实践案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、序列化日期设置

1. 序列化日期时的JSON日期格式化处理

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GongHuiNewtonsoft.Json;

namespace JSONDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime date = new DateTime(2015, 12, 11);
            string json = JsonConvert.SerializeObject(date);
            Console.WriteLine(json);

            string jsonMicrosoft = JsonConvert.SerializeObject(date, new JsonSerializerSettings
            {
                DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
            });
            Console.WriteLine(jsonMicrosoft);
        }
    }
}


2.序列化后的运行结果

 

二、DateFormatString序列化日期设置

1.创建一个DataTime列表,并序列化.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GongHuiNewtonsoft.Json;
using GongHuiNewtonsoft.Json.Serialization;
using GongHuiNewtonsoft.Json.Converters;
using System.Collections.Specialized;

namespace JSONDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            IList<DateTime> list = new List<DateTime>
            {
                new DateTime(2015,12,14,11,33,35,DateTimeKind.Utc),
                DateTime.Now,
                DateTime.Today
            };

            string json = JsonConvert.SerializeObject(list, new JsonSerializerSettings
            {
                DateFormatString = "d MMMM, yyyy HH:mm:ss",
                Formatting = Formatting.Indented
            });

            Console.WriteLine(json);
        }
    }
}


2.运行的结果

三、DateFormatString反序列化日期设置

1.反序列化日期,这个反序列化日期,中间的分隔符与系统的日期分隔符一样。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GongHuiNewtonsoft.Json;
using GongHuiNewtonsoft.Json.Serialization;
using GongHuiNewtonsoft.Json.Converters;
using System.Collections.Specialized;

namespace JSONDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = @"[
                '2015-12-11T00:00:00',
                '2015-12-14 13:23:22'
            ]";

            IList<DateTime> list = JsonConvert.DeserializeObject<IList<DateTime>>(json, new JsonSerializerSettings
            {
                DateFormatString = "yyyy-MM-dd HH:mm:ss"
            });

            foreach (DateTime datetime in list)
            {
                Console.WriteLine(datetime);
            }
        }
    }
}


2.运行的结果

 

JSON源代码下载地址:http://download.youkuaiyun.com/detail/lovegonghui/9342751

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值