Skip to content Skip to sidebar Skip to footer

Deserializing JSON As A Generic List

I have a filter string as shown in the below format: {'groupOp':'AND','rules':[{'field':'FName','op':'bw','data':'te'}]} I need to deserialize this as a Generic list of items. Can

Solution 1:

Have a look at JSON.NET. It allows you to do things like:

JObject o = new JObject(
  new JProperty("Name", "John Smith"),
  new JProperty("BirthDate", new DateTime(1983, 3, 20))
  );

JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));

Console.WriteLine(p.Name);
// John Smith

Source: the documentation.


Solution 2:

Try using the JavaScriptSerializer class like so:

Deserialization code

using System.Web.Script.Serialization;

...

string json = "{\"groupOp\":\"AND\",\"rules\":[{\"field\":\"FName\",\"op\":\"bw\",\"data\":\"te\"}]}";
JavaScriptSerializer serializer = new JavaScriptSerializer();
Filter filter = (Filter)serializer.Deserialize<Filter>(json);

Classes

public class Filter
{
    public string GroupOp { get; set; }
    public List<Rule> Rules { get; set; }

    public Filter()
    {
        Rules = new List<Rule>();
    }
}

public class Rule
{
    public string Field { get; set; }
    public string Op { get; set; }
    public string Data { get; set; }
}

Post a Comment for "Deserializing JSON As A Generic List"