Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavascriptSerializer, Deserializer, not able to deserialize my object

Tags:

json

c#

.net

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.

like image 615
NSN Avatar asked Oct 09 '12 02:10

NSN


2 Answers

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);
like image 110
Jacob Avatar answered Nov 02 '22 03:11

Jacob


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"}"

like image 35
Adam Avatar answered Nov 02 '22 03:11

Adam