Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Discriminator for class hierarchies #29

Open
jnm2 opened this issue Sep 10, 2018 · 2 comments
Open

Discriminator for class hierarchies #29

jnm2 opened this issue Sep 10, 2018 · 2 comments

Comments

@jnm2
Copy link

jnm2 commented Sep 10, 2018

If a type is virtual, the possibility exists that you might need to serialize a piece of information to identify which concrete class to use. Derived or implementing classes may have the same set of properties but signify different things as in a discriminated union, so an additional property should probably be synthesized to identify the correct concrete type.

A "$type"-style property is dangerous and not very pretty. With JSON.NET I usually have a JsonConverter that looks like this (very old implementation):

JsonSerializerSettings.Converters.Add(
    new DerivedDiscriminatorConverter<SomeBaseType>("type")
        .Map<ConcreteType1>("1")
        .Map<ConcreteType2>("2"));

It adds the property "type": "1" for ConcreteType1 and "type": "2" for ConcreteType2. Names are usually more interesting and enum-like. This way known (and vetted!) concrete implementations will roundtrip correctly in an object graph.

I wonder if something similar would make sense for Gu.Xml, maybe even built in?

@JohanLarsson
Copy link
Member

<?xml version="1.0" encoding="utf-16"?>
<WithTwoPublicMutableBoxedProperties xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Value1 xsi:type="xsd:int">1</Value1>
  <Value2 xsi:type="xsd:double">2</Value2>
</WithTwoPublicMutableBoxedProperties>

XmlSerializer does ^

@jnm2
Copy link
Author

jnm2 commented Sep 11, 2018

What about types that don't map to XSD primitives?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants