Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member name is the same as class during JSON deserialization [duplicate]

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> ?

like image 630
Kenny D. Avatar asked Dec 19 '25 00:12

Kenny D.


2 Answers

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;
}
like image 191
L.B Avatar answered Dec 21 '25 12:12

L.B


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; }
}
like image 23
David L Avatar answered Dec 21 '25 13:12

David L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!