I am unable to deserialize my custom object.
public class UserInfo
{
public int Id1 { get; set; }
public string Code { get; set; }
public int Id2 { get; set; }
public List<string> Roles { get; set; }
public string Eg1 { get; set; }
public DateTime Time{ get; set; }
public string Eg2 { get; set; }
public string Version { get; set; }
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Deserialize<UserInfo>(raw);
The Deserialize is throwing an exception
"Cannot convert object of type 'System.String' to type 'UserInfo'"
JSON Contents:
"\"{\\\"Id1\\\":0,\\\"Code\\\":null,\\\"Id2\\\":0,\\\"Roles\\\":null,\\\"Eg1\\\":\\\"Eg2\\\",\\\"Time\\\":\\\"\\\\/Date(-62135596800000)\\\\/\\\",\\\"Version\\\":\\\"1.0.0.0\\\"}\""
Note: Let me know, if it is unclear. I'll edit the question.
-- edited. ID2 changed to Id2. The real class is different in terms of variable names. Hence the issue.
Your string is a C# string containing a JavaScript string containing JSON. Short of fixing what you're being sent, here's how you would deserialize:
var jsonString = serializer.Deserialize<string>(raw);
return serializer.Deserialize<UserInfo>(jsonString);
You are passing a Javascript string to your deserializer because you have your object within an escaped string.
After unescaping it, this is what the serializer receives:
"{\"Id1\":0,\"Code\":null,\"Id2\":0,\"Roles\":null,\"Eg1\":\"Eg2\",\"Time\":\"\\/Date(-62135596800000)\\/\",\"Version\":\"1.0.0.0\"}"
What you really want to send it is:
{"Id1":0,"Code":null,"Id2":0,"Roles":null,"Eg1":"Eg2","Time":"\/Date(-62135596800000)\/","Version":"1.0.0.0"}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With