为了账号安全,请及时绑定邮箱和手机立即绑定

有时数组有时对象反序列化JSON

有时数组有时对象反序列化JSON

C#
浮云间 2019-11-29 09:37:22
我在使用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,有时value是一个数组,有时是“”(空字符串)我的转换器看起来像: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的值为“永久链接”。我可以在交换机中清楚地看到JsonToken.PropertyName没有大小写。在转换器中我需要做些不同的事情吗?谢谢你的帮助。
查看完整描述

3 回答

  • 3 回答
  • 0 关注
  • 363 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信