JsonSerializationException "Unable to find constructor" on Xamarin.Android

I have this very strange problem with my code, and this is a fairly new problem, given that I did not have it six months ago. In short, I made an app in Xamarin and released it about half a year ago in all 3 stores (App Store, Google Play, and Microsoft Store).

Yesterday, the user reported a problem with the Android application, and after I received the fix and recompiled, now I am facing a new error with Json.NET

The exception is

Newtonsoft.Json.JsonSerializationException: Unable to find a constructor to use for type Rowlog.Common.Dtos.CompressedTripData. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'tripCoordinates', line 1, position 19. 

And before you ask, yes, Rowlog.Common.Dtos.CompressedTripData really has a constructor without parameters (well, it doesn’t have one at all, that we all know, it's the same thing).

And, as I said, this is when I download the CompressedTripData object from the server to the Android device. Downloading the same object on iOS and Windows Phone works smoothly. I guess this should be the last change in Json.NET or Xamarin.Android that causes this (other applications still use the Json.NET libraries about six months ago. Not sure if any updates have been made to it since)

Has anyone else encountered a similar problem, and if so, how did you fix it?

+5
source share
2 answers

On the "Android Settings" tab of the project properties, there is a "linker" tab. Is the option selected in the Link drop-down list only with Sdk Assemblies? Or is it "Sdk and custom builds"?

If this is the last one, the constructor without parameters is skipped when binding, because it is not used. Therefore, change it only to "Sdk Assemblies".

+13
source

The Preserve attribute is a more targeted way of ensuring that the member is not deleted by the linker, if you still prefer it to do this with your code at all.

Example:

 [Preserve] [JsonConstructor] private AlertRequest(bool fake_arg) { // fake_arg is to have a unique ctor that we exclusively // use in JSON de-serialization via JsonConstructor attribute. // Preserve attribute ensures Xamarin linker does not remove, // as there are no direct uses of this ctor in the code base } 
+1
source

Source: https://habr.com/ru/post/1211056/


All Articles