Earlz
Earlz

Reputation: 63905

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

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?

Upvotes: 4

Views: 9624

Answers (2)

DeveloperX
DeveloperX

Reputation: 4683

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

Upvotes: 0

codeprogression
codeprogression

Reputation: 3441

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

Upvotes: 8

Related Questions