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?

5
  • 2
    Use json.net from nuget (newtonsoft.json) Commented Mar 24, 2016 at 6:49
  • serialize.Deserialize<SortDescriptor>(fixSortString); Commented Mar 24, 2016 at 6:53
  • @JeremyThompson I have edited my question. Commented Mar 24, 2016 at 6:55
  • @GeneR It works for me. Thanks. Commented Mar 24, 2016 at 6:58
  • That's my 2nd answer Commented Mar 24, 2016 at 7:00

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.