2012-11-22 71 views
0

我需要序列化一个对象数组作为JSON字典。如何将对象数组序列化为JSON字典?

这样的数组项:

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

是否有可能:

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"}, 
    }; 

我希望如下序列化? ContractResolver附近的东西?

谢谢。

回答

1

使用JavaScriptSerializer

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

JavaScriptSerializer js = new JavaScriptSerializer(); 
string json = js.Serialize(keyValues); 
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 })); 
相关问题