反序列化JSON对象

时间:2014-07-04 11:27:39

标签: c# json json.net

我收到一个JsonSerializationException,它声明我需要一个JSON数组而不是一个数组。

class Boards
{
    public List<Board> boards { get; set; }        
}

class Board
{
    public string board { get; set; }
    public string title { get; set; }
    public int ws_board { get; set; }
    public int per_page { get; set; }
    public int pages { get; set; }
}

var boardsJsonLink = "https://a.4cdn.org/boards.json";

WebClient wc = new WebClient();
var json = wc.DownloadString(boardsJsonLink);
var data = JsonConvert.DeserializeObject<List<Boards>>(json);

我在最后一行代码(右上方)得到了异常。

2 个答案:

答案 0 :(得分:0)

您的JSON不是Boards列表,它甚至不是一个集合。您的JSON是属性板的对象,此属性值是集合以及 Boards 类。您应该将其反序列化为Boards类的实例。

var data = JsonConvert.DeserializeObject<Boards>(json);

答案 1 :(得分:0)

请检查以下code

TESTED&amp;工作精细

  protected void btntest_Click(object sender, EventArgs e)
    {
        var boardsJsonLink = "https://a.4cdn.org/boards.json";
        WebClient wc = new WebClient();
        var json = wc.DownloadString(boardsJsonLink);
        var data = JsonConvert.DeserializeObject<TestObj>(json);
        Response.Write(@"<table  width='300px' border='1' cellpadding='2' cellspacing='2'> <tr>
            <td>
                Board</td>
            <td>
                Title</td>
            <td>
               ws_Board</td>
            <td>
                perPage</td>
            <td>
               pages</td>
        </tr>");
        foreach (var itm in data.boards)
        {
            string board = itm.board;
            string title = itm.title;
            int ws_board = itm.ws_board;
            int per_page = itm.per_page;
            int pages = itm.pages;
            Response.Write(@"<tr>
            <td>"+board+"</td><td>"+Title+"</td><td> "+ws_board+"</td><td> "+ per_page+"</td> <td>"+ pages+"</td></tr>");
        }
        Response.Write(@"</table>");
    }

public class Board
{
    public string board { get; set; }
    public string title { get; set; }
    public int ws_board { get; set; }
    public int per_page { get; set; }
    public int pages { get; set; }
}

public class TestObj
{
    public List<Board> boards { get; set; }
}

注意:根据您的要求更改班级名称

<强>输出:

enter image description here