ChrisCa
ChrisCa

Reputation: 11006

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

Upvotes: 3

Views: 10218

Answers (2)

Brian Agnew
Brian Agnew

Reputation: 272217

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.

Upvotes: 1

L.B
L.B

Reputation: 116098

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

Upvotes: 9

Related Questions