如何转换List< T>到特定的Json格式 [英] How to convert a List<T> to specific Json format

查看:70
本文介绍了如何转换List< T>到特定的Json格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to be able to convert a List<T> into a specific JSON table-like format. In my case, the T will always be a simple object (no nested properties). Here are two examples to illustrate what I want.

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

Example #1: List<Person> to 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

Example #2: List<Address> to 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以这种方式序列化对象?如果没有,我该怎么做?谢谢.

Is there a way to tell JSON.net to serialize an object in this manner? If not, how could I accomplish this? Thanks.

由于@Hightechrider的回答,我能够编写一些解决问题的代码.

Thanks to @Hightechrider's answer, I was able to write some code that solves the problem.

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

You can view a working example here https://gist.github.com/1153155

推荐答案

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

Using reflection you can get a list of properties for the type:

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

给出Person p的一个实例,您可以得到以下属性值的枚举:

Given an instance of a Person p you can get an enumeration of the property values thus:

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

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

Wrap those up in a generic method, add your favorite Json serialization and you have the format you want.

这篇关于如何转换List&lt; T&gt;到特定的Json格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆