我有一个自定义对象的列表,该对象具有两个需要序列化为JSON的属性。这是对象:

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


我需要JSON来返回列表,如下所示:

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


这可能吗?

最佳答案

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) });

09-11 20:51