Monday, 15 August 2011

c# - Deserializing descendent objects -


I'm communicating with a JSON-based API that I can not change. It always gives the Response object inside a different result object. Usually this looks like this:

{"ver": "2.0", "result": {"code": 0}}

Definitely adding the additional properties gives the result to 'increment':

{"ver": "2.0", "result": {"code": 0, "hostName" : "Sample", "hostPort": 5000}}

I used Newtonsoft to define objects as follows:

 Internal class RpcResponse {[JsonProperty (PropertyName = "ver")] Public String Version {get; Set; } [Jasonproporty (property name = "result")] Public RPCRPS result results (get); Set; } Internal square RPCRPS pressure {{Jasonproperty (property name = "code")} {get public spatial code; Set; }} Internal Square RpcExtendedResponseResult: RpcResponseResult {[JsonProperty (PropertyName = "hostName")] Public string hostname {received; Set; } [Jasonproperty (PropertyName = "Hostport")] {Received Public Entity Hostport; Set; } 

But when the response object is deserialized:

 RpcResponse rspResponse = JsonConvert.DeserializeObject & LT; RpcResponse> (rspString); 

The result is that the property always appears as an RPCRPSpont result object, that is, JsonConvert does not know to make it as a RPC-connected Response Result Object.

Is there any way with attributes or converters to restore the right ambient object? I think I'm missing something clear!

Because the type of object is RpcResponseResult it. Deserializer can only deselect the fields that have been declared in the type of field specified, because a class "host name" is its own now an RpcExtendedResponseResult.

If I were doing this, I could do a container for all possible areas with the fundamental values, if necessary, and then you can fill other objects as needed.

  Internal class RPCRPSpoint resultcontainer [[Jasonproporty (property name = "code")] {Public receipt code; Set; } [Jasonproporty (PropertyName = "Hostname")] Private string mHostName = string.Empty; Public string hostname {get {return mHostName;} set {mHostName = value; }} [Jasonproperty (PropertyName = "Hostport")] Private In Amohostport = -1; Public integer HostPort {get {return mHostPort;} set {mHostPort = value;}}  

then if in fact you want your object You could do something in your container class like this:

  public RpcResponseResult GetActualResponseType () {if (HostPort = -1 & amp; string.IsNullOrEmtpy (hostname) )!) {New RpcExtendedResponseResult Return () {Code = this.Code, Hostname = this.HostName, HostPort = this.HostPort}; } Return the new RPCRPS page result () {code = this.code}; }  

No comments:

Post a Comment