I'm communicating with a JSON-based API which I can't change. It always returns a Response object with a varying Result object inside. Typically it looks like this:
{ "ver": "2.0", "result": { "code": 0 } }
For certain commands the Result object is 'grown' by adding extra properties:
{ "ver": "2.0", "result": { "code": 0, "hostName": "sample", "hostPort": 5000 } }
I've used Newtonsoft attributes to define the objects as follows:
internal class RpcResponse { [JsonProperty(PropertyName = "ver")] public string Version { get; set; } [JsonProperty(PropertyName = "result")] public RpcResponseResult Result { get; set; } internal class RpcResponseResult { [JsonProperty(PropertyName = "code")] public int Code { get; set; } } internal class RpcExtendedResponseResult: RpcResponseResult { [JsonProperty(PropertyName = "hostName")] public string HostName { get; set; } [JsonProperty(PropertyName = "hostPort")] public int HostPort { get; set; }
But when the Response object is deserialized:
RpcResponse rspResponse = JsonConvert.DeserializeObject<RpcResponse>(rspString);
Its Result property always appears as an RpcResponseResult object, ie. JsonConvert doesn't know to construct it as a RpcExtendedResponseResult object.
Is there some way with Attributes or Converters to reinstate the correct descendent object? I feel like I'm missing something obvious!