JSON.net无法解决反序列化问题

时间:2016-11-25 23:55:01

标签: c# json json.net

我正在尝试反序列化以下内容:

[
   {
      "items":[
         {
            "b":1,
            "Q":"data"
         },
         {
            "b":2,
            "Q":"more data"
         }
      ]
   },
   {
      "seconds_ago":1
   }
]

我尝试使用

反序列化为C#对象
   public class Rootobject
    {
        public Class1[] Property1 { get; set; }
    }

    public class Class1
    {
        public Item[] items { get; set; }
        public int seconds_ago { get; set; }
    }

    public class Item
    {
        public int b { get; set; }
        public string Q { get; set; }
    }

public void test()
{
    Rootobject deserializedObject = JsonConvert.DeserializeObject<Rootobject>(json);
}

但无论我尝试什么,我都会抛出各种错误,明显的用户错误。

任何人都可以告诉我如何使用JSON.net解析上面的示例吗?

2 个答案:

答案 0 :(得分:3)

我想知道你从哪里得到Json,或者你自己想出来了。它不是Json的最佳选择,但由于这是你的示例,我将向您展示如何使用映射模型对其进行反序列化。

映射

正确的类(对于你提供的Json)进行映射将看起来像这样::

public class Item
{
    public int b { get; set; }
    public string Q { get; set; }
}

public class Rootobject
{
    public List<Item> items { get; set; }
    public int? seconds_ago { get; set; }
}

反序列化:

要反序列化它,请使用List<Rootobject>作为类型,因为有多个根对象(因为它是一个数组)[]

List<Rootobject> deserializedList = JsonConvert.DeserializeObject<List<Rootobject>>(json);

答案 1 :(得分:-2)

这是你的解决方案:

using System;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        var data = @"{
    'Property1': [{
        'items': [{
            'b': 1,
            'Q': 'data'
        }, {
            'b': 2,
            'Q': 'more data'
        }],
        'seconds_ago': 1
    }]
}";
        Rootobject deserializedObject = JsonConvert.DeserializeObject<Rootobject>(data);
        Console.WriteLine(deserializedObject.Property1[0].items[0].b);
        Console.WriteLine(deserializedObject.Property1[0].items[0].Q);
        Console.WriteLine(deserializedObject.Property1[0].items[1].b);
        Console.WriteLine(deserializedObject.Property1[0].items[1].Q);
        Console.WriteLine(deserializedObject.Property1[0].seconds_ago);
    }
}

public class Rootobject
    {
        public Class1[] Property1 { get; set; }
    }

    public class Class1
    {
        public Item[] items { get; set; }
        public int seconds_ago { get; set; }
    }

    public class Item
    {
        public int b { get; set; }
        public string Q { get; set; }
    }

你可以在这里试试: https://dotnetfiddle.net/33ZPyX

问题主要是你的json和你的对象的结构。他们不匹配。看看那个小提琴你应该明白为什么。

相关问题