Serialize into a keyword dictionary using Json.Net?

Hello, I am trying to serialize an object to a hash, but I am not getting what I want.

the 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 value of the result jsonis equal

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

As a result, I want:

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

How to make JSON like that?

+4
source share
2 answers

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 the result: [{"foo":"bar"},{"biz":"baz"}]you can do it ...

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 the same data type, so the results are part of the same array. The second is different data types, so you get a different array

+8
source

you can create your own list of key values ​​as

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

he should solve your problem

0

All Articles