开发者

Serialize an object using DataContractJsonSerializer as a json array

开发者 https://www.devze.com 2022-12-31 00:31 出处:网络
I have a class which contains a list of items. I want to serialize an instance of this class to json using the DataContractJsonSerializer as a json array. eg.

I have a class which contains a list of items. I want to serialize an instance of this class to json using the DataContractJsonSerializer as a json array. eg.

class MyClass 
{
    List<MyItem> _items;
}

class MyItem
{
   public string Name {get;set;}
   public string Description {get;set;}
}

When serialized to json it should be like this 开发者_Go百科:

[{"Name":"one","Description":"desc1"},{"Name":"two","Description":"desc2"}]


[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);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号