Reputation: 297
I have a class like
[DataContract]
public class BranchFormTemplate
{
[DataMember]
public BasicSettingsTemplate BasicSettings { get; set; }
[DataMember]
public LclSeedingSettingsTemplate LclSeedingSettings { get; set; }
.
.
.
which I'm trying to instantiate based on a JSON file that is POSTed to the server. What I have is like
HttpPostedFileBase file = Request.Files[0]
HttpInputStream stream = file.InputStream;
var dcs = new DataContractSerializer(typeof(BranchFormTemplate));
BranchFormTemplate branchFormTemplate = dcs.ReadObject(stream) as BranchFormTemplate;
and I get the exception
There was an error deserializing the object of type BranchFormTemplate. The data at the root level is invalid. Line 1, position 1.
What confuses me is that this is a System.Xml.XmlException
and I'm trying to read JSON, not XML. I basically ripped my code from examples on the internet where the source was JSON format, so I can't figure out what I'm missing here.
Upvotes: 1
Views: 1520
Reputation: 101633
DataContractSerializer
documentation states:
Serializes and deserializes an instance of a type into an XML stream or document using a supplied data contract.
To deserialize json, you need DataContractJsonSerializer
:
Serializes objects to the JavaScript Object Notation (JSON) and deserializes JSON data to objects.
Note that if you have a choice - there are better alternatives for parsing JSON. The most widely used one is JSON.NET
(Newtonsoft.Json
).
Upvotes: 2