我需要将一个对象数组序列化为JSON字典。
这样的数组项:
class Entry {
public string Id{get;set;}
public string Value{get;set;}
}
像
这样的数组var arr = new[]
{
new Entry{Id = "one", Value = "First"},
new Entry{Id = "two", Value = "Second"},
new Entry{Id = "tri", Value = "Third"},
};
我希望按如下方式序列化:
{
one: {Title: "First"},
two: {Title: "Second"},
tri: {Title: "Third"}
}
有可能吗? ContractResolver附近的东西?
感谢。
答案 0 :(得分:3)
使用Json.Net
string json = JsonConvert.SerializeObject(
arr.ToDictionary(x => x.Id, x => new { Title = x.Value }));
string json2 = new JavaScriptSerializer()
.Serialize(arr.ToDictionary(x => x.Id, x => new { Title = x.Value }));
答案 1 :(得分:1)
使用JavaScriptSerializer
:
var keyValues = new Dictionary<string, string>
{
{ "one", "First" },
{ "two", "Second" },
{ "three", "Third" }
};
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(keyValues);