从List <t>和显示值</t>序列化JSON

时间:2013-05-29 18:07:49

标签: c# json list serialization

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

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

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

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

这可能吗?

3 个答案:

答案 0 :(得分: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) });

答案 1 :(得分: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();

答案 2 :(得分: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"}]