The service I'm dealing returning different objects nested into a generic object. Here are sample mockup results from service
{"date":1591430887.591481,"results":[{"identity":"result_type_a","result":{"attr_a":1591427634}}]}
{"date":1591430887.591481,"results":[{"identity":"result_type_b","result":{"attr_b":1591427634,"attr_bb":3591457634}}]}
{"date":1591430887.591481,"results":[{"identity":"result_type_c","result":{"attr_c":1591427634,"attr_cc":3591457634,"attr_cc":59634}},{"identity":"result_type_d","result":{"attr_d":"rfrvr","attr_dd":"ytur"}}]}
I tried creating a generic object with declaring result attribute as string. And planning that I could deserialize to the returning json to that generic object, check identity attribute and deserilize the string in result attribute to specific object type.
Here is the object structure
public class GeneralResponse
{
[JsonProperty("date")]
public double Date { get; set; }
[JsonProperty("results")]
public List<GenericResults> Results { get; set; }
}
public class GenericResults
{
[JsonProperty("identity")]
public string Identity { get; set; }
[JsonProperty("result")]
public string Result { get; set; }
}
To serialize/deserialize I'm using Newtonsoft library and the code is below
public static GeneralResponse SerializeResponse(string response)
{
return JsonConvert.DeserializeObject<GeneralResponse>(response);
}
Unfortunately I got following exception while deserializing generic object.
"Unexpected character encountered while parsing value: {. Path 'results[0].result', line 1, position 71."
If I declare Result property of GenericResult as object as below
public class GenericResults
{
[JsonProperty("identity")]
public string Identity { get; set; }
[JsonProperty("result")]
public object Result { get; set; }
}
I can pass first serialization and make the second serialization without getting any exception.
string inner_object = response.Result.ToString();
switch (type)
{
case ResponseTypes.type_A: return JsonConvert.DeserializeObject<ObjectTypeA>(inner_object);
case ResponseTypes.type_B: return JsonConvert.DeserializeObject<ObjectTypeB>(inner_object);
case ResponseTypes.type_C: return JsonConvert.DeserializeObject<ObjectTypeC>(inner_object);
default: throw new Exception("Unknown Response Type");
}
But returned object does not contain the data. I would appreciate any help about modeling this algorithm. Thanks in advance.