JsonExSerializer是一个.NET的Json序列化和反序列化库。近日在用JsonExSerializer解析twitter数据时发现,它无法反序列化Json时间日期类型的字段。经过一番摸索,找到解决办法,就是给它的Context里加一个自己的处理器,处理时间日期类型:
public class DateTimeHandler : IExpressionHandler
{
public bool CanHandle(JsonExSerializer.Framework.Expressions.Expression expression)
{
return expression.ResultType.Equals(typeof(DateTime));
}
public bool CanHandle(Type objectType)
{
if (objectType.Equals(typeof(DateTime)))
{
return true;
}
return false;
}
public object Evaluate(JsonExSerializer.Framework.Expressions.Expression expression, object existingObject, IDeserializerHandler deserializer)
{
//Tue Feb 23 13:43:42 +0000 2010
//-> Feb 23 2010 13:43:42 +0000
var fields = expression.ToString().Split(' ');
return Convert.ToDateTime(fields[1] + " " + fields[2] + " " + fields[5] + " " + fields[3] + " " + fields[4]);
}
public object Evaluate(JsonExSerializer.Framework.Expressions.Expression expression, IDeserializerHandler deserializer)
{
//Tue Feb 23 13:43:42 +0000 2010
//-> Feb 23 2010 13:43:42 +0000
var fields = expression.ToString().Split(' ');
return Convert.ToDateTime(fields[1] + " " + fields[2] + " " + fields[5] + " " + fields[3] + " " + fields[4]);
}
public JsonExSerializer.Framework.Expressions.Expression GetExpression(object data, JsonExSerializer.Framework.Expressions.JsonPath currentPath, IExpressionBuilder serializer)
{
return null;
}
public bool IsReferenceable(object value)
{
return true;
}
}
{
public bool CanHandle(JsonExSerializer.Framework.Expressions.Expression expression)
{
return expression.ResultType.Equals(typeof(DateTime));
}
public bool CanHandle(Type objectType)
{
if (objectType.Equals(typeof(DateTime)))
{
return true;
}
return false;
}
public object Evaluate(JsonExSerializer.Framework.Expressions.Expression expression, object existingObject, IDeserializerHandler deserializer)
{
//Tue Feb 23 13:43:42 +0000 2010
//-> Feb 23 2010 13:43:42 +0000
var fields = expression.ToString().Split(' ');
return Convert.ToDateTime(fields[1] + " " + fields[2] + " " + fields[5] + " " + fields[3] + " " + fields[4]);
}
public object Evaluate(JsonExSerializer.Framework.Expressions.Expression expression, IDeserializerHandler deserializer)
{
//Tue Feb 23 13:43:42 +0000 2010
//-> Feb 23 2010 13:43:42 +0000
var fields = expression.ToString().Split(' ');
return Convert.ToDateTime(fields[1] + " " + fields[2] + " " + fields[5] + " " + fields[3] + " " + fields[4]);
}
public JsonExSerializer.Framework.Expressions.Expression GetExpression(object data, JsonExSerializer.Framework.Expressions.JsonPath currentPath, IExpressionBuilder serializer)
{
return null;
}
public bool IsReferenceable(object value)
{
return true;
}
}
反序列化时把这个处理器加上去即可:
var serializer = new Serializer(typeof(List<Tweet>));
serializer.Context.ExpressionHandlers.Add(new DateTimeHandler());
return serializer.Deserialize(result) as List<Tweet>;
serializer.Context.ExpressionHandlers.Add(new DateTimeHandler());
return serializer.Deserialize(result) as List<Tweet>;