0

I have a couple of classes that look something like this:

public class Address
{
    public string Country { get; set; }
    public string Zip { get; set; }
    public string State { get; set; }
    public string City { get; set; }
    public string Street { get; set; }
}

public class Order
{
    public Address FromAddress { get; set; }
    public Address ToAddress { get; set; }
    public decimal Amount { get; set; }
    ...
}

I'm using Newtonsoft.JSON to serialize/deserialize those objects to JSON, but I have some rather specific requirements for how serializing should work.

For one, properties should all be snake case. This was easy enough using a SnakeCaseNamingStrategy with a contract resolver. However, I also want to bring the properties from the addresses up to the top level and have them renamed to append from or to to them. Basically:

{
    "from_country": "US",
    ...
    "to_country": "US",
    ...
    "amount": "10.00"
}

I want to do all this without littering my classes with attributes and ideally without creating wrapper classes. I've been looking into the creation of custom ContractResolvers as well as custom JsonWriters, but I'm unable to figure out which or which combination of the two I need to achieve my desired format.

James Parsons
  • 6,097
  • 12
  • 68
  • 108
  • 2
    use [AutoMapper](https://docs.automapper.org/en/stable/Getting-started.html) – Akshay G Sep 13 '21 at 15:49
  • 1
    You need to use a custom JsonConverter. See e.g. [Can I serialize nested properties to my class in one operation with Json.net?](https://stackoverflow.com/q/30175911/3744182) and [JSON.Net throws StackOverflowException when using `[JsonConvert()]`](https://stackoverflow.com/q/29719509/3744182). Do those two questions answer yours sufficiently, or do you need additional help? – dbc Sep 13 '21 at 15:54

0 Answers0