0

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

谢谢。

4

2 回答 2

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 }));
于 2012-11-22T22:27:00.297 回答
1

使用JavaScriptSerializer

var keyValues = new Dictionary<string, string>
           {
               { "one", "First" },
               { "two", "Second" },
               { "three", "Third" }
           };

JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(keyValues);
于 2012-11-22T22:25:16.683 回答