Why when I want to serialize in JSON some sort of control, then recursion?

JavaScriptSerializer serializer = new JavaScriptSerializer(); string json = serializer.Serialize(label1); 
  • because the control has a link to the parental control, and the list of links to children is closed - Igor
  • @Igor, damn it is now clear, thanks) - alex-rudenkiy
  • @Igor and there are no ways to make it primitive, in the sense of leaving to serialize the basic properties like name, margin, width, heigth and 3 events (mouse click down, mouse click move and mouse click up)? - alex-rudenkiy
  • Probably you can - write your own wrapper, which has only those properties that you want to keep. - Igor
  • @Igor what do you mean by the word "wrapper"? - alex-rudenkiy

3 answers 3

Because the control has a link to the parental control, and in addition the list of links to children is closed.

You can write your own wrapper, which has only those properties that you want to keep.

 public class ControlWrapper { private Control fControl; public ControlWrapper(Control aControl) { fControl = aControl; } public int Width { get { return fControl.Width; } } ... } JavaScriptSerializer serializer = new JavaScriptSerializer(); string json = serializer.Serialize(new ControlWrapper(label1)); 
  • Sorry for the stupid question, but how to use it? :) - alex-rudenkiy
  • sorry, added two lines - Igor
  • Ah, everything is clear now, thanks: D - alex-rudenkiy

Because you are trying to serialize non-serializable: UI controls. Controls are not intended for serialization, because they have an internal state and internal bindings (for example, event subscriptions) that cannot be saved during serialization.

Do it right, save the model, not the view. Cut corners will not work.

  • Well, how to prepare as a model? I understand, a class, a structure, an object, and the model will still be similar to the controls. - alex-rudenkiy
  • @ alex-rudenkiy: No, it will not. For example, you don’t need a Parent reference to a top-level element (for example, a Grid ) in the model. Or to the list of animations. - VladD

Once you are using wpf, you can try XAML serialization.

  • Perfect, but one major drawback is that it does not save events 😔 - alex-rudenkiy