I am trying to serialise a collection of objects using json.net
The object looks like this:
public class TaxBand
{
public TaxBand(string county, decimal taxPercentage)
{
County = county;
Tax = taxPercentage;
}
public string County { get; private set; }
public decimal Tax { get; private set; }
}
and they are contained in a structure like this:
var data = new Dictionary<string, List<TaxBand>>();
data = PopulateDataset();
string json = JsonConvert.SerializeObject(data, Formatting.Indented);
This produces json that looks like this:
{
"North": [
{
"County": "Merseyside",
"Tax": 5.0
},
{
"County": "Greater Manchester",
"Tax": 6.0
}
],
"South": [
{
"County": "Greater London",
"Tax": 5.5
},
{
"County": "Surry",
"Tax": 6.2
}
]
}
is it possible to produce json that looks like this:
{
"North":
{
"Merseyside": 5.0,
"Greater Manchester" : 6.0
},
"South":
{
"Greater London": 5.5,
"Surry": 6.2
}
}
Am happy to consider changing the shape of any objects, or indeed use a different serialisation library
With the help of some Linq
var data = new Dictionary<string, List<TaxBand>>();
data = PopulateDataset();
var data2 = data.ToDictionary(kv => kv.Key,
kv => kv.Value.ToDictionary(t=>t.County,t=>t.Tax) );
var s = JsonConvert.SerializeObject(data2,Newtonsoft.Json.Formatting.Indented);
OUTPUT:
{
"North": {
"Merseyside": 5.0,
"Greater Manchester": 6.0
},
"South": {
"Greater London": 5.5,
"Surry": 6.2
}
}
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