JSON反序列化

时间:2011-08-26 11:56:18

标签: c# json

这是我的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"}] 

我必须反序列化它应该怎么做?请帮忙

2 个答案:

答案 0 :(得分:2)

你在那里的JSON代表一组看起来像视频的对象,所以首先你需要定义一个类来存储每个视频,如下所示:

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

完成此操作后,您可以使用内置或第三方的众多JSON库之一。在这个例子中,我使用了JSON.NET。这是指向documentation的链接。

接下来,您将需要使用JsonConvert类的DeserializeObject静态泛型方法,如此指定List<Video>类型,以便它知道要反序列化的JSON是Video对象的集合:< / p>

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

完成此操作后,您可以使用一组Video对象。

希望这会对你有所帮助。

答案 1 :(得分:1)

您可以使用System.Web.Extensions dll中的JavaScriptSerializer反序列化json,可以在以下位置找到:

  

C:\ Program Files \ Reference   组件\微软\ Framework.NETFramework \ V4.0 \ System.Web.Extensions.dll

在项目中添加对DLL的引用后添加:

using System.Web.Script.Serialization;

您还需要将Target Framework设置为非客户端配置文件,例如:

  

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