从List和显示值

本文关键字:显示 List | 更新日期: 2023-09-27 18:16:01

我有一个包含两个属性的自定义对象列表,需要序列化为JSON。下面是对象:

public class IndexData
{
  public string ColumnName { get; set; }
  public string Data { get; set; }
}

我需要JSON的列表返回如下:

{ "IndexData" : [
    { "Column1": "Data1",
      "Column2": "Data2"
    } 
  ]
}

这可能吗?

从List<T>和显示值

List<IndexData> list = new List<IndexData>()
{
    new IndexData(){ColumnName="column1",Data="data1"},
    new IndexData(){ColumnName="column2",Data="data2"},
};
//Using Json.Net
var json1 = JsonConvert.SerializeObject(
                new {IndexData=list.ToDictionary(x => x.ColumnName, x => x.Data)});
//Using JavaScriptSerializer
var json2 = new JavaScriptSerializer().Serialize(
                new { IndexData = list.ToDictionary(x => x.ColumnName, x => x.Data) });

使用JavaScriptSerializer

var indexdata = new IndexData();
var json = new JavaScriptSerializer().Serialize(indexdata);

OR DataContractJsonSerializer

MemoryStream s = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(IndexData));
s.Position = 0;
StreamReader sr = new StreamReader(s);
var json = sr.ReadToEnd();

我是Json的忠实粉丝。净

你可以使用SerializeObject调用来简单地序列化你的对象:

var list = new List<IndexData> {new IndexData {ColumnName = "Foo", Data = "Bar"}};
var output = JsonConvert.SerializeObject(list);
然后将

output设置为

[{"ColumnName":"Foo","Data":"Bar"}]