2

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 :

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

2
  • 3
    And what is the problem you have? Do you have a question about this? Commented May 16, 2010 at 16:19
  • Also FWIW you should check out the Json.NET serializer as it is far more performant than the WCF Json serializer. Commented May 16, 2010 at 16:29

1 Answer 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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

The problem is, List<MyItem> HAS to be member of MyClass, and MyClass should be serialized as array... so graph would be instance if MyClass and the items will be added to this instance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.