Serialize into a key-value dictionary with Json.Net?

拥有回忆 提交于 2019-12-10 18:05:20

问题


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

Code:

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

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"}]

How do I made the JSON come out like that?


回答1:


Try this for the last line of your method:

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

Result: {"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




回答2:


you can create your own key value list like

 class mylist:Dictionary<string,object>
{
}
var l=new mylist<Data>();
l.Add("foo","bar");

it should solve your problem



来源:https://stackoverflow.com/questions/6862177/serialize-into-a-key-value-dictionary-with-json-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!