我有一个包含项目列表的类。 我想使用DataContractJsonSerializer作为json数组将此类的实例序列化为json。例如
class MyClass
{
List<MyItem> _items;
}
class MyItem
{
public string Name {get;set;}
public string Description {get;set;}
}
当序列化为json时,它应该是这样的:
[{"Name":"one","Description":"desc1"},{"Name":"two","Description":"desc2"}]
答案 0 :(得分:6)
[DataContract]
public class MyItem
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Description { get; set; }
}
class Program
{
static void Main()
{
var graph = new List<MyItem>
{
new MyItem { Name = "one", Description = "desc1" },
new MyItem { Name = "two", Description = "desc2" }
};
var serializer = new DataContractJsonSerializer(graph.GetType());
serializer.WriteObject(Console.OpenStandardOutput(), graph);
}
}