JSON.NET反序列化 [英] JSON.NET deserialization

查看:127
本文介绍了JSON.NET反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JSON.NET的新手,正在尝试将JSON字符串反序列化为简单的.NET对象. 这是我的代码段:

I'm new with JSON.NET and I'm trying to deserialize a JSON string to a simple .NET object. Here is a snippet of my code:

public void DeserializeFeed(string feed)
{
    JsonSerializer ser = new JsonSerializer();
    Post deserializedPost = JsonConvert.DeserializeObject<Post>(feed);

    if (deserializedPost == null)
        MessageBox.Show("JSON ERROR !");
    else
    {
        MessageBox.Show(deserializedPost.titre);
    }
}

我这样做

MessageBox.Show(deserializedPost.titre);

我总是会收到此错误:

值不能为空.

Value can not be null.

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

Here is my object that I want to fill with the retrieved JSON element:

using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace MeltyGeeks
{
    public class Post
    {
        public String titre { get; set; }
        public String aresum { get; set; }

        // Constructor
        public Post()
        {
        }
    }
}

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

And here is a snippet of my JSON string:

{"root_tab":{"tab_actu_fil":{"data":[{"c_origine":"MyApp",
"titre":"title of first article",
"aresum":"this is my first Article
"tab_medias":{"order":{"810710":{"id_media":810710,"type":"article","format":"image","height":138,"width":300,"status":null}}}},

推荐答案

您显示的JSON结构与Post对象不匹配.您可以定义其他类来表示此结构:

The JSON structure you have shown doesn't match the Post object. You could define additional classes to represent this structure:

public class Root
{
    public RootTab root_tab { get; set; }
}

public class RootTab
{
    public ActuFil tab_actu_fil { get; set; }
}

public class ActuFil
{
    public Post[] Data { get; set; }
}

public class Post
{
    public String titre { get; set; }
    public String aresum { get; set; }
}

然后:

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

或者如果您不想定义那些其他对象,则可以执行以下操作:

or if you don't want to define those additional objects you could do this:

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

这篇关于JSON.NET反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆