Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json serialisation formatting

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

like image 945
ChrisCa Avatar asked Sep 26 '26 08:09

ChrisCa


1 Answers

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
  }
}
like image 93
L.B Avatar answered Sep 28 '26 21:09

L.B