0

I have a json string like {field:'DateToEnd',dir:'asc'}

And i have a class in c# with following two properties.

public class SortDescriptor
{
    public SortDescriptor()
    {
    }
    public string Field { get; set; }
    public string Dir { get; set; }
}

Now i want to convert this string to the class object so that i can access the properties.

I tried the following example. But it's not working for me.

JavaScriptSerializer serialize = new JavaScriptSerializer();
SortDescriptor sort = (SortDescriptor)serialize.DeserializeObject(fixSortString);

It gives following error:

Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type 'NF.Common.SortDescriptor'.

Can anyone let me know that how i can do this?

Code Rider
  • 2,003
  • 5
  • 32
  • 50

1 Answers1

0

I'm pretty sure DeserializeObject requires a type as a second parameter, eg

JavaScriptSerializer serialize = new JavaScriptSerializer();
SortDescriptor sort = (SortDescriptor)serialize.DeserializeObject(fixSortString, typeof(SortDescriptor));

Or using Generics:

JavaScriptSerializer serialize = new JavaScriptSerializer(); 
SortDescriptor sort = (SortDescriptor)serialize.DeserializeObject<SortDescriptor>(fixSortString);
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321