0

In my VS2017 EF-Core 2.2 solution, I have 3 projects:

  1. Backend: WebServer - storing data in SQLServer, delivering data with NewtonSoft.Json
  2. DataModels - classes used to create tables in SQLServer (Backend) and SQLite (Frontend)
  3. Frontend: Xamarin.Forms app - using SQLite, getting data with NewtonSoft.Json

The Backend contains a project reference to the DataModels project.

Since my local SQLite database stores just a subset of the content defined in the DataModels classes, I did not add a project reference to the DataModels project, but created a Windows 10 symbolic link in my Frontend project to the DataModels directory, which allows me to modify the DataModel classes like

namespace DataModels
{
    [Table("Info")] // Used for front- and backend
    public abstract class BaseInfo
    {
        public Guid Id { get; set; }

        [Required]
        [StringLength(200)]
        public string Title { get; set; }

#if FRONTEND // Only available on frontend side
        [NotMapped]
        public bool IsSelected {get; set;}
#endif

#if !FRONTEND // Only available on backend side
        [Required]
        [StringLength(25)]
        public MediaProcessingStateEnum MediaProcessingState { get; set; }
#endif
    }
}

This is quit nice, but now I have the problem, that the Backend serializes the data with NewtonSoft.Json adding the $type item to it (since there are abstract classes) but when I want to deserialize the json content on the Frontend side using

var info = JsonConvert.DeserializeObject<Info>(content, new JsonSerializerSettings
{
        TypeNameHandling = TypeNameHandling.Auto
});

the deserializer can not create an instance of the class, because the (typeinfo) link to the DataModels assembly is missing!

"Error resolving type specified in JSON 'DataModels.Info, DataModels'. Path '$type', line 1, position 41."

Could someone please give me an idea, how to solve the 'missing reference' problem in NewtonSoft.Json deserializer, without giving up the concept described above?

x y
  • 911
  • 9
  • 27
  • You could create a custom [`ISerializationBinder`](https://www.newtonsoft.com/json/help/html/SerializeSerializationBinder.htm) to manually map the type and assembly names to the correct type(s). See [deserialize type handled json using Newtonsoft library between different applications](https://stackoverflow.com/q/44207280/3744182), [JSON.Net: deserializing polymorphic types without specifying the assembly](https://stackoverflow.com/q/13598969) or [Using a custom type discriminator to tell JSON.net which type of a class hierarchy to deserialize](https://stackoverflow.com/q/11099466/3744182). – dbc Mar 12 '19 at 16:56
  • Using a custom serialization binder will also improve the security of your app, see [TypeNameHandling caution in Newtonsoft Json](https://stackoverflow.com/q/39565954/3744182) for why. – dbc Mar 12 '19 at 16:57
  • Great, I will try this asap – x y Mar 12 '19 at 21:23

0 Answers0