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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With