Serialize object using DataContractJsonSerializer as json array

I have a class that contains a list of items. I want to serialize an instance of this class to json using 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 something like this:

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

+2


a source to share


1 answer


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

      



+6


a source







All Articles