I am getting this error when using my class.
Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace
[DataContract]
public class EntryData
{
[DataMember]
public string EntryId { get; set; }
[DataMember]
public string EmailAddress { get; set; }
[DataMember]
public string StatusCode { get; set; }
[DataMember]
public string TotalVoteCount { get; set; }
public static T Deserialise<T>(string json)
{
var obj = Activator.CreateInstance<T>();
using (var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
memoryStream.Position = 0;
var serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(memoryStream); // getting exception here
return obj;
}
}
}
string responseJson = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
var results = EntryData.Deserialise<EntryData>(response)
I have seen online that it has to do with the memoryStream position
BUT as you can see i am setting it to the beginning.
Please help.
I don't set StatusCode or TotalVoteCount when passing JSON in. I don't think this is the problem though.
{
"EntryId":"43",
"EmailAddress":"[email protected]"
}
Instead of using Deserialize method in my class I am using now this.
//commented out this code.
string responseJson = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
var results = EntryData.Deserialise<EntryData>(response)
// this is the way to go using JavaScriptSerializer
var serializer = new JavaScriptSerializer();
var results = serializer.Deserialize<EntryData>(response);
Could it be caused by your JSON names not matching your property names in C#?
My understanding is that
{
"FirstName" : "Mark"
}
Would be able to deserialize into:
[DataContract]
public class Person
{
[DataMember]
public string FirstName {get; set;}
}
but this wouldn't be able to serialize
{
"Name" : "Mark"
}
unless you changed your C# class to have an explicit name for the DataMember
[DataContract]
public class Person
{
[DataMember(Name="Name")]
public string FirstName {get; set;}
}
I'm not sure which error this would cause though. I Don't have enough first hand experience.