2

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

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

我需要像这样返回 List 的 JSON:

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

这可能吗?

4

3 回答 3

2
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) });
于 2013-05-29T18:14:34.603 回答
0

采用JavaScriptSerializer

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

或者DataContractJsonSerializer

MemoryStream s = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(IndexData));
s.Position = 0;
StreamReader sr = new StreamReader(s);
var json = sr.ReadToEnd();
于 2013-05-29T18:09:05.537 回答
0

我是Json.Net的忠实粉丝

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

var list = new List<IndexData> {new IndexData {ColumnName = "Foo", Data = "Bar"}};

var output = JsonConvert.SerializeObject(list);

output然后将设置为

[{"ColumnName":"Foo","Data":"Bar"}]
于 2013-05-29T18:15:08.900 回答