如何在C#中解析JSON子集合

时间:2012-07-10 22:03:32

标签: c# json

编辑:下面的问题似乎是放在“items”数组上的“bars”标签。我试图使用“JavaScriptSerializer”和“NewtonSoft”工具,当该集合到位时它会出错。 错误:无法将当前JSON对象(例如{\“name \”:\“value \”})反序列化为     输入'System.Collections.Generic.List ...

我从调用RESTful Web服务获得了一个JSON返回字符串。 我已经想出如何把它变成C#对象。

示例JSON:

{
"property1": "value1",
"property2": "value2"
}

JSON解析为的示例类:

public class FooClass
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}

我在System.Web.Extensions命名空间中使用“JavaScriptSerializer”类...效果很好!

现在,如果JSON有一个集合项呢? 像这样:

{
"property1": "value1",
"property2": "value2",
"bars": {
"items": [
{
"sub_property1": "sub_value1",
"sub_property2": "sub_value2"
},
...
]
}
}

我想为我的“FooClass”课做类似的事情:

public class FooClass
{
public string Property1 { get; set; }
public string Property2 { get; set; }
public List<BarClass> Bars { get; set; }
}

public class BarClass
{
public string Sub_Property1 { get; set; }
public string Sub_Property2 { get; set; }
}

有没有办法告诉JavaScriptSerializer类“items”数组等于“Bars”,这样它们就可以“解析”到类中了?

感谢您在此提供任何建议。

2 个答案:

答案 0 :(得分:1)

当然 - 这种行为会自动发生。重要的是你的BarClass有一个无参数构造函数(我认为这对于序列化类来说也很常见)。 JavaScriptSerializer反序列化方法接受您的类型,用于重构对象并遍历您类中的所有子类型。

From the documentation on MSDN:“在反序列化期间,引用了序列化程序的当前类型解析程序,它确定了在转换嵌套在数组和字典类型中的元素时要使用的托管类型。因此,反序列化过程会遍历所有嵌套的输入元素。“

using System.Collections.Generic; 
using System.Web.Script.Serialization;
namespace ConsoleApplication1
{
    class Program
    {


        private static void Main(string[] args)
        {
            var person = new Person();
            person.Name = "reacher gilt";
            person.Address = "100 East Way";
            person.Age = 74; 
            person.Aliases = new List<string>(new []{"teddy", "freddy", "eddy", "Betty"});
            person.Bars = new List<BarClass>(new[]{ 
                new BarClass("beep","boop"),
                new BarClass("meep","moop"),
                new BarClass("feep","foop"),
            });
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            string jsonString = serializer.Serialize(person);

            var rehydrated = serializer.Deserialize<Person>(jsonString);
        }

    }


    class Person
    {
        public string Name { get; set; }

        public string Address { get; set; }

        public int Age { get; set; }

        public List<string> Aliases;
        public List<BarClass> Bars { get; set; }
    }
    class BarClass
    { 
        public string Sub_Property1 { get; set; }
        public string Sub_Property2 { get; set; }
        public BarClass() { }
        public BarClass (string one, string two)
        {
            Sub_Property1 = one;
            Sub_Property2 = two;
        }
    }
}

编辑:在教练抢劫澄清评论之后:

using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace ConsoleApplication1
{
    class Program
    {


        private static void Main(string[] args)
        {
            var person = new Person();
            person.Name = "reacher gilt";
            person.Address = "100 East Way";
            person.Age = 74; 
            person.Aliases = new List<string>(new []{"teddy", "freddy", "eddy", "Betty"});
            person.Bars = new Dictionary<string, List<BarClass>>();

            person.Bars.Add("items",
                new List<BarClass>(new[]{ 
                new BarClass("beep","boop"),
                new BarClass("meep","moop"),
                new BarClass("feep","foop"),
            }));
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            string jsonString = serializer.Serialize(person);

            var rehydrated = serializer.Deserialize<Person>(jsonString);
        }

    }


    class BarClass
    { 
        public string Sub_Property1 { get; set; }
        public string Sub_Property2 { get; set; }
        public BarClass() { }
        public BarClass (string one, string two)
        {
            Sub_Property1 = one;
            Sub_Property2 = two;
        }
    }

    class Person
    {
        public string Name { get; set; }

        public string Address { get; set; }

        public int Age { get; set; }

        public List<string> Aliases;
        public Dictionary <string, List<BarClass> >Bars { get; set; }
    }
}

让你像json一样:

{
    "Aliases":
    [
        "teddy",
        "freddy",
        "eddy",
        "Betty"
    ],
    "Name":"reacher gilt",
    "Address":"100 East Way",
    "Age":74,
    "Bars":
    {
        "items":
        [
            {
                "Sub_Property1":"beep",
                "Sub_Property2":"boop"
            },

            {
                "Sub_Property1":"meep",
                "Sub_Property2":"moop"
            },

            {
                "Sub_Property1":"feep",
                "Sub_Property2":"foop"
            }
        ]
    }
}

我也看到有人使用DataContractJsonSerializer,它确实单向序列化为json,但问题中指定了System.Web.Script.Serialization.JavaScriptSerializer。

答案 1 :(得分:0)

试试这个:

[DataContract]
public class FooClass
{
    [DataMember]
    public string Property1 { get; set; }

    [DataMember]
    public string Property2 { get; set; }

    [DataMember]
    public Bars Bars { get; set; }
}

[DataContract]
public class Bars
{
    [DataMember]
    public List<Item> Items { get; set; }
}

[DataContract]
public class Item
{
    [DataMember]
    public string Sub_Property1 { get; set; }

    [DataMember]
    public string Sub_Property2 { get; set; }
}