简体   繁体   English

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

[英]How to serialize array of object as JSON dictionary?

I need to serialize an array of objects as JSON dictionary. 我需要将对象数组序列化为JSON字典。

Array item like this: 这样的数组项:

class Entry {
    public string Id{get;set;}
    public string Value{get;set;}
}

So array like 所以数组像

var arr = new[]
    {
        new Entry{Id = "one", Value = "First"},
        new Entry{Id = "two", Value = "Second"},
        new Entry{Id = "tri", Value = "Third"},
    };

I expect to be serialized as follows: 我希望序列化如下:

{
    one: {Title: "First"},
    two: {Title: "Second"},
    tri: {Title: "Third"}
}

Is it possible? 可能吗? Something near ContractResolver? ContractResolver附近有东西吗?

Thanks. 谢谢。

Using Json.Net 使用Json.Net

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

or JavaScriptSerializer JavaScriptSerializer

string json2 = new JavaScriptSerializer()
             .Serialize(arr.ToDictionary(x => x.Id, x => new { Title = x.Value }));

Use the JavaScriptSerializer : 使用JavaScriptSerializer

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

JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(keyValues);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM