我使用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,会出现错误:Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[FacebookMedia]。 因为在JSON中,Media不是一个集合,所以这个错误是有道理的。
我发现了这篇文章,它描述了类似的问题,所以我尝试走这条路线:Deserialize JSON, sometimes value is an array, sometimes "" (blank string)
我的转换器看起来像:
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的值是"permalink"。明显可以看到,在switch语句中没有为JsonToken.PropertyName设置case。
我的转换器需要做什么不同的事情吗?感谢任何帮助。