Customise Json Serialisation of properties per class

Viewed 73

The new System.Text.Json serialiser supports setting a naming policy as follows:

var options = new JsonSerializerOptions {
    PropertyNamingPolicy = myPolicy
}

However these options are applied across the whole serialisation event.

I want to customise properties in different ways for different classes. In my scenario, I have two classes, both inherit from Dictionary<string, object> and supply additional properties. I want the KEYS of class A to be serialised as all lowercase field names, while the KEYS of class B should be serialised as lowercase with a special string prefix.

Deserialisation is not a concern or consideration for this code.

Edit: I do need the properties on the dictionary serialised as well and have noticed this doesn't happen currently.

Eg.

public class Product : Dictionary<string, object> {
    public string ProductId { get; set; }
    public IList<Store> Stores { get; set; }
}
public class Store : Dictionary<string, object> {
    public string StoreId { get; set; }
}
...
IEnumerable<Product> products = GetProducts();    

Output expected for 'products':

[
  {
    "productid": "1234",
    "somefield" "fhsdjkfsd",
    "stores": [
      {
        "storeid": "abc",
        "prefix_somefield": "somevalue",
        "prefix_foo": "bar"
      },
      {
        "storeid": "def",
        "prefix_another": "val"
      }
    ]
  }
  {
    "productid": "456",
    "anotherfield": "fjaskdas"
  }
]
0 Answers
Related