使用Json.Net序列化为键值字典吗?

问题描述:

你好,我正在尝试将一个对象序列化为哈希,但是我没有得到想要的东西.

Hello I'm trying to serialize an object into a hash, but I'm not getting quite what I want.

代码:

class Data{
  public string Name;
  public string Value;
}
//...
var l=new List<Data>();
l.Add(new Data(){Name="foo",Value="bar"});
l.Add(new Data(){Name="biz",Value="baz"});
string json=JsonConvert.SerializeObject(l);

执行此操作时,json结果值为

when I do this the json result value is

[{"Name":"foo","Value":"bar"},{"Name":"biz","Value":"baz"}]

但是我想要的结果是这样:

The result I want however is this:

[{"foo":"bar"},{"biz":"baz"}]

如何使JSON像这样出来?

How do I made the JSON come out like that?

尝试此方法作为您方法的最后一行:

Try this for the last line of your method:

string json = JsonConvert.SerializeObject(l.ToDictionary(x=>x.Name, y=>y.Value));

结果:{"foo":"bar", "biz":"baz"}

对于结果:[{"foo":"bar"},{"biz":"baz"}],您可以执行此操作...

For result: [{"foo":"bar"},{"biz":"baz"}] you can do this...

string json = JsonConvert.SerializeObject(new object[]{new {foo="bar"}, new {biz = "baz"} });

OR

string json = JsonConvert.SerializeObject(new object[]{new Data1{foo="bar"}, new Data2{biz = "baz"} });

第一个结果假定相同的数据类型,因此结果是同一数组的一部分.第二种是不同的数据类型,因此您得到了不同的数组

The first result assumes same data type, so results are part of same array. The second is different data types, so you get a different array