Reputation: 499
I've searched for a solution to my problem for quite a while now and seen some ideas that I thought might work out, but I haven't been able to put it all together. Worth mentioning is that I'm quite new to C#.
I have a library that defines a bunch of model classes that is used to deserialize JSON-data into. One of these models are Application
that has the property public List<ApplicationField> Fields { get; set; }
I've been able to make a sub class of Application that I call MyApplication
. Since I have MyApplication
I would also like to have MyApplicationField
that extends ApplicationField
I've tried a few approaches and below is the one that I thought had the best chance of succeeding (Unfortunately it didn't):
public class MyApplication : Application
{
new public List<MyApplicationField> Fields { get; set; }
}
The Json is then deserialized by the code:
JsonConvert.DeserializeObject<MyApplication>
I was hoping that the value of the JSON Fields
property would be mapped into the Fields property of type List<MyApplicationField>
that I've defined in my subclass MyApplication
. However it is deserialized into the base class' Fields
property (Which is of type List<ApplicationField>
)
Note: I am not able to alter the base classes.
Is it possible to achieve the behavior I'm looking for?
Upvotes: 0
Views: 372
Reputation: 56566
Works for me, as the default behavior. Can you provide an example demonstrating the issue?
void Main()
{
{
var jsonData = @"{""Fields"":[{""MyProp"":""my prop value"",""Prop1"":""prop 1 value""}]}";
var myApp = JsonConvert.DeserializeObject<MyApplication>(jsonData);
Console.WriteLine(myApp.Fields[0].MyProp); // "my prop value"
Console.WriteLine(((Application)myApp).Fields == null); // "True"
}
{
// just to make sure it's not being clever because "MyProp" is specified
// we'll try this also, which could be deserialized as an Application
var jsonData = @"{""Fields"":[{""Prop1"":""prop 1 value""}]}";
var myApp = JsonConvert.DeserializeObject<MyApplication>(jsonData);
Console.WriteLine(myApp.Fields[0].Prop1); // "prop 1 value"
Console.WriteLine(((Application)myApp).Fields == null); // "True"
}
}
public class MyApplication : Application
{
public new List<MyApplicationField> Fields { get; set; }
}
public class Application
{
public List<ApplicationField> Fields { get; set; }
}
public class MyApplicationField : ApplicationField
{
public string MyProp { get; set; }
}
public class ApplicationField
{
public string Prop1 { get; set; }
}
Upvotes: 1