3

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

Kenny D.
  • 927
  • 3
  • 11
  • 29

2 Answers2

5

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;
}
L.B
  • 114,136
  • 19
  • 178
  • 224
0

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; }
}
David L
  • 32,885
  • 8
  • 62
  • 93