DataContractJsonSerializer exception

I get this error when using my class.

Error

Waiting for the root element from the namespace ''. Encounted 'None' with name '', namespace

My class

[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; } } } 

USING

 string responseJson = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd(); var results = EntryData.Deserialise<EntryData>(response) 

I saw online that it has to memoryStream position with the memoryStream position BUT, as you can see that I am setting it to the beginning.

Please, help.

Json goes to handler

I do not set StatusCode or TotalVoteCount when passing JSON. I do not think this is a problem.

 { "EntryId":"43", "EmailAddress":" test@email.com " } 

ANSWER

Instead of using the Deserialize method in my class, I use this now.

 //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); 
+4
source share
2 answers

Could this be caused by your JSON names not matching your property names in C #?

I understand that

 { "FirstName" : "Mark" } 

You can deserialize:

 [DataContract] public class Person { [DataMember] public string FirstName {get; set;} } 

but that could not be serialized

 { "Name" : "Mark" } 

if you have not 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 am not sure which error this will cause. I lack first-hand experience.

+3
source

Do you think this could be an encoding problem? Have you tried using Encoding.UTF8 instead of Unicode?

All the examples that I saw with the DataContractSerializer used UTF-8 encoding.

Encoding.Unicode is UTF-16 encoding.

I cannot find any documentation explicitly indicating which encodings the DataContractSerializer supports. I guess that would be reasonable enough to detect the correct encoding, but I don't know the encodings very well. Perhaps in this case it is really impossible.

0
source

Source: https://habr.com/ru/post/1490909/


All Articles