JSON.NET反序列化

前端之家收集整理的这篇文章主要介绍了JSON.NET反序列化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 JSON.NET的新手,我正在尝试将JSON字符串反序列化为一个简单的.NET对象.
这是我的代码片段:
  1. public void DeserializeFeed(string Feed)
  2. {
  3. JsonSerializer ser = new JsonSerializer();
  4. Post deserializedPost = JsonConvert.DeserializeObject<Post>(Feed);
  5.  
  6. if (deserializedPost == null)
  7. MessageBox.Show("JSON ERROR !");
  8. else
  9. {
  10. MessageBox.Show(deserializedPost.titre);
  11. }
  12. }

当我做

  1. MessageBox.Show(deserializedPost.titre);

我总是得到这个错误

Value can not be null.

这是我的对象,我想填充检索到的JSON元素:

  1. using System.Net;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using System.Windows.Documents;
  5. using System.Windows.Ink;
  6. using System.Windows.Input;
  7. using System.Windows.Media;
  8. using System.Windows.Media.Animation;
  9. using System.Windows.Shapes;
  10.  
  11. namespace MeltyGeeks
  12. {
  13. public class Post
  14. {
  15. public String titre { get; set; }
  16. public String aresum { get; set; }
  17.  
  18. // Constructor
  19. public Post()
  20. {
  21. }
  22. }
  23. }

这是我的JSON字符串的片段:

  1. {"root_tab":{"tab_actu_fil":{"data":[{"c_origine":"MyApp","titre":"title of first article","aresum":"this is my first Article
  2. "tab_medias":{"order":{"810710":{"id_media":810710,"type":"article","format":"image","height":138,"width":300,"status":null}}}},
显示的JSON结构与Post对象不匹配.您可以定义其他类来表示此结构:
  1. public class Root
  2. {
  3. public RootTab root_tab { get; set; }
  4. }
  5.  
  6. public class RootTab
  7. {
  8. public ActuFil tab_actu_fil { get; set; }
  9. }
  10.  
  11. public class ActuFil
  12. {
  13. public Post[] Data { get; set; }
  14. }
  15.  
  16. public class Post
  17. {
  18. public String titre { get; set; }
  19. public String aresum { get; set; }
  20. }

然后:

  1. string Feed = ...
  2. Root root = JsonConvert.DeserializeObject<Root>(Feed);
  3. Post post = root.root_tab.tab_actu_fil.Data[0];

或者如果您不想定义这些额外的对象,您可以这样做:

  1. var root = JsonConvert.DeserializeObject<JObject>(Feed);
  2. Post[] posts = root["root_tab"]["tab_actu_fil"]["data"].ToObject<Post[]>();
  3. string titre = posts[0].titre;

猜你在找的Json相关文章