如何用JSON.NET序列化从List派生的类型为类似数组的对象
本文关键字:类型 对象 数组 派生 JSON 何用 NET 序列化 List | 更新日期: 2023-09-27 18:07:20
考虑以下从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设置,可以为我做这个吗?
我认为最简单的方法得到你正在寻找的东西,是做这样的事情:
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);
}