如何使用JSON.NET将从List派生的类型序列化为类数组对象

时间:2015-08-11 20:56:59

标签: c# serialization json.net

考虑以下来自List

的类
public class Foo : List<string>
{
    public string Bar { get; set; }
}

使用JSON.NET对其进行序列化会转储Bar属性并生成常规数组:

var foo = new Foo() { "a", "b", "c" };
foo.Bar = "baz";
JsonConvert.SerializeObject(foo); // ["a","b","c"]

作为序列化的结果,我该怎么做才能获得以下类似数组的对象?

{"0": "a", "1": "b", "2": "c", "length": 3, "bar": "baz"}

自定义序列化程序是唯一可行的方法,还是有JSON.NET设置可以为我做这个?

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法来获得你想要的东西,就是做这样的事情:

var foo = new Foo() { "a", "b", "c" };
foo.Bar = "baz";

var data = foo
    .Select((value, index) => new { value, index })
    .ToDictionary(wrapper => wrapper.index.ToString(), wrapper => (object)wrapper.value);

data.Add("length", foo.Count);
data.Add("bar", foo.Bar);

var json = JsonConvert.SerializeObject(data);
//{"0":"a","1":"b","2":"c","length":3,"bar":"baz"}

更通用的方法为所有具有任何数量属性的元素解决此问题将是此代码:

var foo = new Foo() { "a", "b", "c" };
foo.Bar = "baz";
foo.Beer = "beer";

var json = GetJsonWithItemsAndProperties(foo);
//{"0":"a","1":"b","2":"c","length":3,"Bar":"baz","Beer":"beer"}

//...//

private static string GetJsonWithItemsAndProperties<T>(IReadOnlyCollection<T> listWithProperties)
{
    var data = listWithProperties
        .Select((value, index) => new {value, index})
        .ToDictionary(wrapper => wrapper.index.ToString(), wrapper => (object) wrapper.value);

    data.Add("length", data.Count);

    listWithProperties.GetType()
        .GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance |
                        System.Reflection.BindingFlags.DeclaredOnly).ToList()
        .ForEach(p => data.Add(p.Name, p.GetValue(listWithProperties)));

    return JsonConvert.SerializeObject(data);
}