我在使用 JSON.NET 库反序列化从 Facebook 返回的数据时遇到了一些麻烦。
从一个简单的墙贴返回的 JSON 如下所示:
{
"attachment":{"description":""},
"permalink":"http://www.facebook.com/permalink.php?story_fbid=123456789"
}
为照片返回的 JSON 如下所示:
"attachment":{
"media":[
{
"href":"http://www.facebook.com/photo.php?fbid=12345",
"alt":"",
"type":"photo",
"src":"http://photos-b.ak.fbcdn.net/hphotos-ak-ash1/12345_s.jpg",
"photo":{"aid":"1234","pid":"1234","fbid":"1234","owner":"1234","index":"12","width":"720","height":"482"}}
],
一切都很好,我没有问题。我现在遇到了一个来自移动客户端的简单墙贴,其中包含以下 JSON,并且反序列化现在失败了,这一个帖子:
"attachment":
{
"media":{},
"name":"",
"caption":"",
"description":"",
"properties":{},
"icon":"http://www.facebook.com/images/icons/mobile_app.gif",
"fb_object_type":""
},
"permalink":"http://www.facebook.com/1234"
这是我反序列化的类:
public class FacebookAttachment
{
public string Name { get; set; }
public string Description { get; set; }
public string Href { get; set; }
public FacebookPostType Fb_Object_Type { get; set; }
public string Fb_Object_Id { get; set; }
[JsonConverter(typeof(FacebookMediaJsonConverter))]
public List<FacebookMedia> { get; set; }
public string Permalink { get; set; }
}
如果不使用 FacebookMediaJsonConverter,我会收到错误消息:无法将 JSON 对象反序列化为类型“System.Collections.Generic.List`1[FacebookMedia]”。这是有道理的,因为在 JSON 中,Media 不是一个集合。
我发现这篇文章描述了一个类似的问题,所以我试图走这条路:反序列化 JSON,有时值是一个数组,有时是“”(空白字符串)
我的转换器看起来像:
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartArray)
return serializer.Deserialize<List<FacebookMedia>>(reader);
else
return null;
}
这工作正常,除了我现在得到一个新的例外:
在 JsonSerializerInternalReader.cs 内部,CreateValueInternal():反序列化对象时出现意外令牌:PropertyName
reader.Value 的值是“永久链接”。我可以在 switch 中清楚地看到 JsonToken.PropertyName 没有案例。
我需要在转换器中做一些不同的事情吗?谢谢你的帮助。