user2883072
user2883072

Reputation: 257

CustomConverter to compare to a property on the same class in web api

I've been writing a few customconverters, extending Newtonsofts JsonConverter and stumbled on a little problem. Say I have two properties on a class, but they cannot be the same value. Is it possible to find the value of another property in a converter... for example, say I have a model like so.

I'd want to be able to check the value of Surname in CustomCompareConverter to ensure its not the same value as Firstname

public class Person
{
    [JsonConverter(typeof(CustomCompareConverter), "Surname")]
    public string Firstname { get; set; }

    public string Surname { get; set; }
}
```

Upvotes: 0

Views: 115

Answers (1)

Fran
Fran

Reputation: 6530

You are trying to do multiple things with the json deserialization process that really should be separated

  1. converting some external json into your domain object

  2. validating the domain object.

The fact that the Surname cannot match the FirstName property is a business rule of your domain. So keep that within your domain. You can:

  1. write a separate validator class that will check the state of your person object and return a list of validation failures
  2. implement IValidatableObject on your Person class and implement the interface
  3. write a custom validator like in this SO question

Use the JSON deserialization process as an anti-corruption layer to keep the details of external systems out of your your domain structure. Once you've take the extenal object and converted it to your domain object then use conventional means to validate that your domain object.

Upvotes: 1

Related Questions