如何将对象数组序列化为JSON字典?

时间:2012-11-22 22:20:17

标签: c# json json.net

我需要将一个对象数组序列化为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附近的东西?

感谢。

2 个答案:

答案 0 :(得分:3)

使用Json.Net

string json = JsonConvert.SerializeObject(
                       arr.ToDictionary(x => x.Id, x => new { Title = x.Value }));

JavaScriptSerializer

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