【问题标题】:Serialize an object using DataContractJsonSerializer as a json array使用 DataContractJsonSerializer 作为 json 数组序列化对象
【发布时间】:2010-05-16 16:17:00
【问题描述】:

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

【问题讨论】:

  • 你有什么问题?您对此有疑问吗?
  • FWIW 你应该检查一下 Json.NET 序列化程序,因为它比 WCF Json 序列化程序性能要好得多。

标签: c# json datacontractserializer datacontractjsonserializer


【解决方案1】:
[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);
    }
}

【讨论】:

  • 问题是,List 必须是 MyClass 的成员,并且 MyClass 应该被序列化为数组......所以如果 MyClass 和项目将被添加到这个实例中,那么图形将是实例
猜你喜欢
  • 2013-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
相关资源
最近更新 更多