2

i have a solution where i consume a WebService using RestSharp providing JSON data. I have a class model like this, matching the received data:

public class PBase
{
    public string Name { get; set; }

    public virtual string GetValue()
    {
        return string.Empty;
    }
}

public class PDouble : PBase
{
    public double DoubleValue { get; set; }
    public string Scale { get; set; }

    public override string GetValue()
    {
        return DoubleValue.ToString(CultureInfo.InvariantCulture);
    }
}

public class PBool : PBase
{
    public bool? BoolValue { get; set; }

    public override string GetValue()
    {
        if (!BoolValue.HasValue)
            return null;
        return BoolValue.Value ? "1" : "0";
    }
}

Meerely deep within the data, such blocks as the following appear multiple times, holding the parameters of a parent object, which is not of much interest here (as everything else except the parameter thingy works fine):

"Parameters":
[
    {
        "__type": "PDouble:http://name.space.de/Parameter",
        "Name": "DEPTH",
        "DoubleValue": 5,
        "Scale": "MM"
    },
    {
        "__type": "PDouble:http://name.space.de/Parameter",
        "Name": "HEIGHT",
        "DoubleValue": 10,
        "Scale": "MM"
    },
    {
        "__type": "PBool:http://name.space.de/Parameter",
        "Name": "ESSENTIAL",
        "BoolValue": true
    },
]

Now, the problem is, the deserialized data contains only PBase instances. So everything except Name is gone. How can i achieve correct deserialization?

EDIT:

For deserialization i have nothing special implemented, just like this:

var client = new RestClient()
{
    BaseUrl = new Uri("MyURL")
};
var request = new RestRequest()
{
    Resource = "MyResource",
    Method = Method.GET
};
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;

var response = client.Execute<MyType>(request);
return response.Data;
schwebbe
  • 90
  • 1
  • 13
  • Can you add the code with the deserializing part? – Ben Jul 20 '17 at 11:13
  • I will update the question, thank you! – schwebbe Jul 20 '17 at 11:24
  • This post will give you more information https://stackoverflow.com/questions/8030538/how-to-implement-custom-jsonconverter-in-json-net-to-deserialize-a-list-of-base – Ben Jul 20 '17 at 11:35
  • Ended up using a snippet from the mentioned post with little changes. Great thanks! Didn't see the solution at the first look... In my case, the discussed KnownTypeConverter fits very well. – schwebbe Jul 21 '17 at 08:10

0 Answers0