Created
March 14, 2018 20:26
-
-
Save Kritner/1b9637b2696b0dc6787cde8c67aac6b3 to your computer and use it in GitHub Desktop.
Potential for flattening an abstract object into JSON for serialization/deserialization?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Test | |
{ | |
public int Id {get;set;} | |
[JsonIgnore] public Foo {get;set;} = new Foo(); | |
public BigInteger Bar | |
{ | |
get => Foo.Bar; | |
set => Foo.Bar = value; | |
} | |
private string _propA; | |
[JsonProperty(PropertyValue = "propA")] | |
public string PropA | |
{ | |
get | |
{ | |
if (Foo.Baz is BazA a) | |
{ | |
return a.PropA; | |
} | |
return null; | |
} | |
set | |
{ | |
_propA = value; | |
// && whatever other properties are not null/not default that | |
// decide on the concrete type | |
if (_propA != null ) | |
{ | |
Foo.Baz = new BazA() | |
{ | |
PropA = _propA, | |
// other properties | |
} | |
} | |
} | |
} | |
private string _propB; | |
[JsonProperty(PropertyValue = "propB")] | |
public string PropB | |
{ | |
get | |
{ | |
if (Foo.Baz is BazB b) | |
{ | |
return b.PropB; | |
} | |
return null; | |
} | |
set | |
{ | |
_propB = value; | |
// && whatever other properties are not null/not default that | |
// decide on the concrete type | |
if (_propB != null ) | |
{ | |
Foo.Baz = new BazB() | |
{ | |
PropB = _propB, | |
// other properties | |
} | |
} | |
} | |
} | |
} | |
public class Foo | |
{ | |
public BigInteger Bar {get;set;} | |
public BazBase Baz {get;set;} | |
} | |
public abstract class BazBase | |
{ | |
} | |
public class BazA : BazBase | |
{ | |
public string PropA {get;set;} | |
} | |
public class BazB : BazBase | |
{ | |
public string PropB {get;set;} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment