您的位置:首页 > Web前端 > JavaScript

JSON使用Error反序列化忽略非法日期

2015-12-11 14:49 399 查看
1.JSON使用Error事件委托来忽略非法的日期,并且不抛出异常.

注意:其中JSON字符串中有三个不是合法日期.

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;

namespace JSONDemo
{
class Program
{
static void Main(string[] args)
{
IList<string> errors = new List<string>();

List<DateTime> d = JsonConvert.DeserializeObject<List<DateTime>>(@"[
'2015-12-11T14:29:00Z',
'这不是一个日期格式',
[1],
'1987-03-23T23:23:23',
null,
'2008-8-1'
]", new JsonSerializerSettings
{
Error = delegate(object sender, ErrorEventArgs args1)
{
errors.Add(args1.ErrorContext.Error.Message);
args1.ErrorContext.Handled = true;
},
Converters = { new IsoDateTimeConverter() }
});
Console.WriteLine(d[0]);
Console.WriteLine(d[1]);
Console.WriteLine(d[2]);
Console.WriteLine(errors[0]);
Console.WriteLine(errors[1]);
Console.WriteLine(errors[2]);
}
}
}


2.运行的结果



JSON源代码下载地址:http://download.csdn.net/detail/lovegonghui/9342751
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: