我希望能够将List<T>转换为特定的JSON表格格式。就我而言,T将始终是一个简单的对象(无嵌套属性)。这里有两个例子来说明我想要的。

范例1:List<Person>转换为JSON

// C# list of Persons
var list = new List<Person>() {
  new Person() { First = "Jesse", Last = "Gavin", Twitter = "jessegavin" },
  new Person() { First = "John", Last = "Sheehan", Twitter = "johnsheehan" }
};

// I want to transform the list above into a JSON object like so
{
  columns : ["First", "Last", "Twitter"],
  rows: [
    ["Jesse", "Gavin", "jessegavin"],
    ["John", "Sheehan", "johnsheehan"]
  ]
}


范例2:List<Address>转换为JSON

// C# list of Locations
var list = new List<Location>() {
  new Location() { City = "Los Angeles", State = "CA", Zip = "90210" },
  new Location() { City = "Saint Paul", State = "MN", Zip = "55101" },
};

// I want to transform the list above into a JSON object like so
{
  columns : ["City", "State", "Zip"],
  rows: [
    ["Los Angeles", "CA", "90210"],
    ["Saint Paul", "MN", "55101"]
  ]
}


有没有办法告诉JSON.net以这种方式序列化对象?如果没有,我该怎么做?谢谢。

更新:

感谢@Hightechrider的回答,我能够编写一些解决问题的代码。

您可以在此处查看工作示例https://gist.github.com/1153155

最佳答案

使用反射,您可以获取该类型的属性列表:

        var props = typeof(Person).GetProperties();


给定Person p的实例,您可以得到属性值的枚举,因此:

        props.Select(prop => prop.GetValue(p, null))


用通用方法将它们包装起来,添加您喜欢的Json序列化,然后便有了所需的格式。

关于c# - 如何将List <T>转换为特定的Json格式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7087312/

10-09 20:24
查看更多