Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

c#

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?

like image 530
Earlz Avatar asked Feb 23 '23 10:02

Earlz


1 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 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

like image 97
codeprogression Avatar answered Mar 06 '23 01:03

codeprogression