clowwindy的杂草牧场

   :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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;
}
}

反序列化时把这个处理器加上去即可:

var serializer = new Serializer(typeof(List<Tweet>));
serializer.Context.ExpressionHandlers.Add(
new DateTimeHandler());
return serializer.Deserialize(result) as List<Tweet>;
posted on 2011-03-20 13:22  clowwindy  阅读(927)  评论(0编辑  收藏  举报