Good day, friends.
There is a project in which dll shapes are connected using reflection. During serialization, all libraries are connected, but when deserializing one of them was deleted. How to make the deserializer skip the type of elements that is no longer present and continue to work correctly with the others?

using (BsonReader reader = new BsonReader(ms)) { var serializer = JsonSerializer.Create(new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, }); shapeCollection.Set(serializer.Deserialize<ShapeCollection>(reader)); } 

With this record, an error occurs:

 Newtonsoft.Json.JsonSerializationException: "Error resolving type specified in JSON 'labN1.Rectangle, Rectangle'. Path 'ShapeList[1].$type'." Внутреннее исключение: JsonSerializationException: Could not load assembly 'Rectangle'. 

Considered on the example of removing the library Rectangle.dll.
Maybe I messed up something, because:

 try { Assembly a = Assembly.Load("аRectangle"); Type type = a.GetType("labN1.FactoryMethodes.RectangleFactory"); object obj = Activator.CreateInstance(type); MethodInfo rectangleFactory = type.GetMethod("CreateObject"); object value = rectangleFactory.Invoke(obj, new object[] { new[] { 120, 30, 40, 50, (Object)Color.Black, 2 } }); shapeCollection.ShapeList.Add((Shape)value); types.Add(value.ToString()); } catch { MessageBox.Show("Rectangle.dll не подключена."); } 

If you make a mistake when connecting the library Rectangle.dll ("aRectangle"), and the library itself is not deleted, then everything will work without errors, but deserialize Rectangle. Which, however, can then be deleted.

    1 answer 1

    Wrote through JSON, the output is 2 methods. The bottom line:

      1) Serialize each object on a new line.
      2) I read the string and try to deserialize it.
      3) If deserialization is successful, then I enter the list, otherwise I process the exception and proceed to step 2
     public void SerializeToJson(String path) { ShapeCollection shapeCollection = ShapeCollection.Instance(); foreach (Shape shape in shapeCollection.ShapeList) { var settings = new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.Objects}; File.AppendAllText(@path, JsonConvert.SerializeObject(shape, settings)); File.AppendAllText(@path, "\r\n"); } } public void DeserializeFromJson(String path) { ShapeCollection shapeCollection = ShapeCollection.Instance(); shapeCollection.ShapeList.Clear(); shapeCollection = ShapeCollection.Instance(); String line; using (StreamReader sr = new StreamReader(@path)) { while (sr.Peek() >= 0) { line = sr.ReadLine(); try { var settings = new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.Objects}; var shape = JsonConvert.DeserializeObject<Object>(line, settings); shapeCollection.ShapeList.Add((Shape)shape); } catch { } } } }