简体   繁体   English

使用DataContractJsonSerializer作为JSON数组序列化对象

[英]Serialize an object using DataContractJsonSerializer as a json array

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. 我想使用DataContractJsonSerializer作为json数组将此类的实例序列化为json。 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 : 当序列化为json时,应该像这样:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用DataContractJsonSerializer将对象序列化为JSON - Unable to Serialize Object to JSON Using DataContractJsonSerializer 使用 DataContractJsonSerializer 将字典序列化为 JSON 对象 - Serialize a Dictionary as JSON object using DataContractJsonSerializer DataContractJsonSerializer:序列化对象或数组(可以是两者) - DataContractJsonSerializer: serialize object or array (can be both) 使用DataContractJsonSerializer从JSON数据填充对象数组时出错 - Error filling an object array from JSON data using DataContractJsonSerializer 如何使用 DataContractJsonSerializer 序列化包含日期和时间属性的 JSON 字符串? - How to serialize JSON string containing date and time property using DataContractJsonSerializer? JSON使用.NET DataContractJsonSerializer序列化器与字典进行序列化/反序列化 - JSON serialize/deserialize with Dictionary using .NET DataContractJsonSerializer serializer 如何使用DataContractJsonSerializer将类类型而不是命名空间序列化为Json字符串 - How to serialize class type but not the namespace to a Json string using DataContractJsonSerializer 使用DataContractJsonSerializer设置JSON对象root - Set JSON object root using DataContractJsonSerializer 如何使用DataContractJsonSerializer序列化/反序列化存储在对象字段中的DateTime? - How to serialize/deserialize a DateTime stored inside an object field using DataContractJsonSerializer? 在C#中使用DataContractJsonSerializer反序列化JSON对象 - Deserialization of JSON object by using DataContractJsonSerializer in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM