2011-08-26 225 views
2

這是我的JSONJSON反序列化

[{"id":23,"name":"Video Clips"},{"id":15,"name":"Deleted Scenes"},{"id":9,"name":"Music Albums"},{"id":7,"name":"Trailers"},{"id":18,"name":"Short Films"},{"id":21,"name":"Movie Clips"},{"id":1,"name":"Movies "},{"id":4,"name":"Plays"},{"id":22,"name":"Scenes"},{"id":2,"name":"TV Show"},{"id":5,"name":"Kids"},{"id":16,"name":"Interviews"},{"id":11,"name":"Film Songs"},{"id":14,"name":"Making of Movie"}] 

我要反序列化,我應該怎麼做呢?請幫助

+5

看看[JSON.NET](http://json.codeplex.com/) –

+0

看看這個鏈接http://stackoverflow.com/questions/7203770/how-to-deserialize-json-in-asp -net – Bobby

+0

如何反序列化JSON這個升C – Mahendra

回答

2

你在那裏的JSON表示一個看起來像視頻的對象數組,因此首先你需要def INE一類以每個視頻存儲,像這樣:

public class Video 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
} 

完成這一操作,您可以利用任何衆多JSON庫的一個內置或第三方。在這個例子中,我使用了JSON.NET。這是一個鏈接到documentation

接下來,您將需要使用像這樣的JsonConvert類的DeserializeObject靜態泛型方法,指定List<Video>類型,以便它知道JSON被反序列化是視頻對象的集合:

using Newtonsoft.Json; 

... 

string json = "[{\"id\":23,\"name\":\"Video Clips\"},{\"id\":15,\"name\":\"Deleted Scenes\"},{\"id\":9,\"name\":\"Music Albums\"},{\"id\":7,\"name\":\"Trailers\"},{\"id\":18,\"name\":\"Short Films\"},{\"id\":21,\"name\":\"Movie Clips\"},{\"id\":1,\"name\":\"Movies \"},{\"id\":4,\"name\":\"Plays\"},{\"id\":22,\"name\":\"Scenes\"},{\"id\":2,\"name\":\"TV Show\"},{\"id\":5,\"name\":\"Kids\"},{\"id\":16,\"name\":\"Interviews\"},{\"id\":11,\"name\":\"Film Songs\"},{\"id\":14,\"name\":\"Making of Movie\"}]"; 

List<Video> videos = JsonConvert.DeserializeObject<List<Video>>(json); 

完成此操作後,您就可以使用視頻對象的集合。

希望這可以幫助你。

1

您可以使用反序列化從JavaScriptSerializer的System.Web.Extensions程序的DLL可以在被發現的JSON:

C:\ Program Files文件\參考 大會\微軟\ Framework.NETFramework \ V4 .0 \ System.Web.Extensions.dll

在項目中添加增加一個參考DLL後:

using System.Web.Script.Serialization; 

而且你還需要將目標框架設置爲一個非客戶端配置文件,例如:

的.NET Framework 4

然後使用代碼像這樣的反序列化json:

var json = @"[{""id"":23,""name"":""Video Clips""},{""id"":15,""name"":""Deleted Scenes""},{""id"":9,""name"":""Music Albums""},{""id"":7,""name"":""Trailers""},{""id"":18,""name"":""Short Films""},{""id"":21,""name"":""Movie Clips""},{""id"":1,""name"":""Movies ""},{""id"":4,""name"":""Plays""},{""id"":22,""name"":""Scenes""},{""id"":2,""name"":""TV Show""},{""id"":5,""name"":""Kids""},{""id"":16,""name"":""Interviews""},{""id"":11,""name"":""Film Songs""},{""id"":14,""name"":""Making of Movie""}]"; 
var jsonSerializer = new JavaScriptSerializer(); 
var deserializedList = jsonSerializer.Deserialize<List<JsonType>>(json); 
+0

謝謝主席先生的寶貴合作mment – Mahendra

+0

@ user913947:您的歡迎:) –