json serialisation formatting

10,148

Solution 1

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

Solution 2

This:

"Merseyside": 5.0

looks to me similar to a single entry in a Dictionary and you may get some mileage from experimenting in that fashion.

However the example JSON looks entirely reasonable. Given that you have clients consuming this I would likely not worry about the serialisation, and would certainly be wary of compromising your object model to reflect a desired serialisation (especially given that it looks legitimate and easy to parse). Note that if you change the serialsiation your clients have to be able to parse this successfully.

If you were to modify the JSON output, rather than compromise your object model, I would isolate that change - copy your TaxBand object into a TaxBandJson object or similar.

Share:
10,148
ChrisCa
Author by

ChrisCa

Updated on June 05, 2022

Comments

  • ChrisCa
    ChrisCa almost 2 years

    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