Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customise NewtonSoft.Json for Value Object serialisation [duplicate]

Sometimes, perhaps in a DDD situation, you might want to use C# to create Value Objects to represent data, to give more meaning to your domain than using primitive types would, with the added benefit of being immutable.

For example:

public class PostalCode // Bit like a zipcode
{
    public string Value { get; private set; }

    public PostalCode(string value)
    {
        Value = value;
    }

    // Maybe sprinkle some ToString()/Equals() overrides here
}

Bravo. Well done me.

The only thing is, when serialised to Json, you get this:

{
    "Value": "W1 AJX"
}

That sort of looks okay, but when it's used as a property of an object (let's say an address) then it looks like this:

{
  "Line1": "Line1",
  "Line2": "Line2",
  "Line3": "Line3",
  "Town": "Town",
  "County": "County",
  "PostalCode": {
    "Value": "W1 AJX"
  }
}

Taken to an extreme, you can see there's a lot of noise here. What I'd like to do, is tell Newtonsoft.Json, that when it sees a type of PostalCode, that it can serialise it to a string value (and vice versa). That would result in the following json:

{
  "Line1": "Line1",
  "Line2": "Line2",
  "Line3": "Line3",
  "Town": "Town",
  "County": "County",
  "PostalCode": "W1 AJX"
}

Is this achievable? I've had a look through the docs and I suspect a custom JsonConverter might be the way forward?

like image 594
Neil Barnwell Avatar asked May 04 '17 10:05

Neil Barnwell


1 Answers

public class PostalCode // Bit like a zipcode
{
    [JsonProperty(PropertyName = "PostalCode")]
    public string Value { get; set; }

    // Maybe sprinkle some ToString()/Equals() overrides here
}

I think this is your answer?

like image 194
TobiasB Avatar answered Oct 02 '22 15:10

TobiasB