Is it possible to serialize views?

DiskHummDiskHumm Member ✭✭
edited May 2018 in Xamarin.Forms

I'm making an app where the order and properties of the views on a page can be changed. I'm trying to serialize the StackLayout that contains the views.

I've tried 3 different serialization techniques, all of which have failed with the following exceptions:

XmlSerializer:

System.InvalidOperationException: There was an error reflecting type 'AppProject.MyApp'. occurred

Newtonsoft.Json:

Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'ParentView' with type 'Xamarin.Forms.StackLayout'. Path 'Pages[0].stack.Children[0]'.

BinaryFormatter:

System.Runtime.Serialization.SerializationException: Type 'AppProject.MyApp' in Assembly 'AppProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

Can someone please recommend a solution?

Thanks.

Answers

  • DiskHummDiskHumm Member ✭✭

    I was actually able to serialize the views by using:

                JsonSerializerSettings settings = new JsonSerializerSettings
                {
                    PreserveReferencesHandling = PreserveReferencesHandling.Objects,
                    Formatting = Formatting.Indented,
                    TypeNameHandling = TypeNameHandling.All
                };
    
                string json = JsonConvert.SerializeObject(myApp, settings);
    

    However, when deserializing with myApp = JsonConvert.DeserializeObject<MyApp>(newjson, settings); I get the this error:

    System.InvalidOperationException: Cannot change ObservableCollection during a CollectionChanged event.

    Does anyone know a way around this?

    Thanks.

  • DiskHummDiskHumm Member ✭✭

    bump

  • JamesLaveryJamesLavery GBBeta, University ✭✭✭✭✭
    As @joemanke says - just serialize the view structure - this is far more lightweight. Otherwise you are serializing huge amounts of internal view data which is not relevant and is likely to be out of date or even wrong when you try to deserialize and use it.
Sign In or Register to comment.