sazr
sazr

Reputation: 25928

Custom Deserialization: use JsonConverter or custom override of Deserialize method?

My C# model Person has properties that don't map nicely to the JSON I am getting from a RESTful request.

C# Model:

class Person {
    public string First { get; set; }
    public string Last  { get; set; }
}

JSON Response:

{
    "customer_first_name": "foo",
    "customer_last_name": "bar"
}  

So when I deserialize the JSOn to a Person model/object I need to map customer_first_name to First and so on (am I correct?). Should I be using a JsonConverter to achieve this? Or custom override of Deserialize method? Or something else?

Upvotes: 1

Views: 79

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38767

Just use the [JsonProperty] attribute.

class Person {
    [JsonProperty(PropertyName = "customer_first_name")]
    public string First { get; set; }
    [JsonProperty(PropertyName = "customer_last_name")]
    public string Last  { get; set; }
}

Upvotes: 1

Related Questions