当然——这种行为是自动发生的。重要的是你的 BarClass 有一个无参数的构造函数(我认为这对于序列化类来说也很常见)。JavaScriptSerializer 反序列化方法接收您的类型以用于重构对象并遍历您的类中的所有子类型。
来自 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;
}
}
}
编辑:在教练 rob 澄清评论后:
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。