2011-09-21 67 views
0

我有一個過濾字符串如在下面的格式:反序列化JSON作爲一個泛型列表

{"groupOp":"AND","rules":[{"field":"FName","op":"bw","data":"te"}]} 

我需要反序列化這個作爲項目的泛型列表。

任何人都可以指導我如何做到這一點?

+0

[DataContracts](http://stackoverflow.com/questions/ 4289073/how-do-datacontracts-work-deserialize-json) –

+1

是的,我創建了一個類並試圖通過使用下面的代碼去掉.IList filterData = new JavaScriptSerializer()。反序列化>(filter); – nivas

+0

您是否編寫了DataContract以存儲反序列化的數據? –

回答

0

嘗試使用JavaScriptSerializer類,如下所示:

反序列化碼

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); 

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

我不認爲這是一個「通用」列表。在這裏你必須定義類,所以如果JSON要改變格式,有人必須更新類。 –

2

看看JSON.NET。它允許你做這樣的事情:

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 

來源:the documentation