I am receiving an Xml String over a network and I want to be able to put the contents of it within an object. When I keep the setters of the class as public, it works totally fine. However, I want to be able to keep them private, in which case I get the following error:
System.InvalidOperationException: 'Cannot deserialize type 'MyApp.Random' because it contains property 'data' which has no public setter.'
I have looked all over the internet and haven't found a solution.
My class is very simple, like this:
public class Random
{
public string data{ get; private set; }
public string abc{ get; private set; }
public string defg{ get; private set; }
}
This is how I'm trying to deserialize it:
var serializer = new XmlSerializer(typeof(Random));
result = (Random)serializer.Deserialize(new StringReader(xmlString));
Fixed it. I just used the DataContractSerializer instead of the XmlSerializer and it worked like a charm. Here is the solution:
var ser = new DataContractSerializer(typeof(Random));
Random result = (Random)ser.ReadObject(new MemoryStream(xmlString));