2

我有一个包含项目列表的类。我想使用 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"}]

4

1 回答 1

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);
    }
}
于 2010-05-16T16:26:03.523 回答