XML Serialization exception on Android after migrating from Unity 2019 to 2020

Viewed 106

I finally migrated my project from Unity 2019.4.28f1 to 2020.3.14f1. After cleaning up a few deprecations everything appeared to be back to normal, however deploying on Android, I am seeing now an issue with XML deserialisation. I get this exception when trying to deserialize data from a string:

NotSupportedException: Parent does not have a default constructor. The default constructor must be explicitly defined.
 
    at System.Reflection.Emit.TypeBuilder.DefineDefaultConstructor (System.Reflection.MethodAttributes attributes) [0x00070] in <1dc10152da894b47b8bbfed156e7b841>:0
    at System.Xml.Serialization.XmlSerializationILGen.GenerateBaseSerializer (System.String baseSerializer, System.String readerClass, System.String writerClass, System.Xml.Serialization.CodeIdentifiers classes) [0x00103] in <d0db3f607625460db8f5df59fe982070>:0
    at System.Xml.Serialization.TempAssembly.GenerateRefEmitAssembly (System.Xml.Serialization.XmlMapping[] xmlMappings, System.Type[] types, System.String defaultNamespace, System.Security.Policy.Evidence evidence) [0x002ed] in <d0db3f607625460db8f5df59fe982070>:0
    at System.Xml.Serialization.TempAssembly..ctor (System.Xml.Serialization.XmlMapping[] xmlMappings, System.Type[] types, System.String defaultNamespace, System.String location, System.Security.Policy.Evidence evid

This is the helper method I am using:

public static T DeserializeXml<T>(this string xml)
    {
        T obj = default(T);

        XmlSerializer serializer = new XmlSerializer(typeof(T));
        using (TextReader textReader = new StringReader(xml))
        {
            obj = (T)serializer.Deserialize(textReader);
        }

        return obj;
    }

That all worked for years w/o issues. These exceptions don’t occur when running in editor, or after deploying to iOS or standalone/desktop. So it seems related to compiling to Android only. I searched around, but haven’t found any concrete clue what the reason is and how to fix it. So any hint welcome!

1 Answers

I have similar problem when use scripting backend=Mono in player settings.

Using IL2CPP option solved my problem:

Player Setting -> Other Settings -> Configuration:

enter image description here

But with this settings, I can't have a development build. Thus this solution is a temporary solution.

Related