I'm trying to deserialize a JSON payload that for reasons outside of my control contain a property (i.e. member) named exactly the same as its class name. Something like:
{
...,
"Id": {
"A" : "Hello",
"B" : "World",
...
"Id" : 1
},
...
}
When I derive a class from this payload, I need something like this:
class Id{
public string A, B;
public int Id;
}
Obviously, the compiler complains with: member names cannot be the same as enclosing type
How can I rename the member (or the class for that effect), so Json.NET (the library I'm using to maker it easier) is able to "hydrate" payloads just by calling JsonConvert.DeserializeObject<T> ?
Use a different name for property, and give a hint to json.net how to deserialize that property...
public class Id
{
public string A {get; set;}
public string B {get; set;}
[JsonProperty("Id")]
public int IdProp;
}
Use the JsonProperty attribute which allows you to specify the name of the source property while mapping to a destination property of a different name.
public class Id
{
public string A { get; set; }
public string B { get; set; }
[JsonProperty("Id")]
public int ExtId { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With