开发者

Deserializing JSON as a Generic List

开发者 https://www.devze.com 2023-04-06 07:25 出处:网络
I have a filter string as shown in the below format: {\"groupOp\":\"AND\",\"rules\":[{\"field\":\"FName\",\"op\":\"bw\",\"data\":\"te\"}]}

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 anyone guide me on how to do this?


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.


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; }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消