码迷,mamicode.com
首页 > Windows程序 > 详细

C# json序列化

时间:2016-05-06 19:31:56      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

直接上图

using System.Runtime.Serialization.Json;
using System.IO;
using System.Collections.Generic

首先定义class

/// <summary>
/// json类
/// </summary>
public class Video
{
public String videoName { get; set; }
public String videoSize { get; set; }
public String videoTime { get; set; }
public String videoType { get; set; }
}

序列化方法

/// <summary>
/// JSON序列化
/// </summary>
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}

反序列化方法

/// <summary>
/// JSON反序列化
/// </summary>
public static T JsonDeserialize<T>(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}

调用单个

/// <summary>
/// 填充json
/// </summary>
/// <param name="context"></param>
/// <returns>返回json序列</returns>
private string getByList(HttpContext context)
{
Video video = new Video();
video.videoName = "测试";
video.videoSize = "2M";
video.videoTime = "70";
video.videoType = "mp4";
String jsonTextString = JsonSerializer<Video>(video);

return jsonTextString;
}

调用多个

/// <summary>
/// 填充json
/// </summary>
/// <param name="context"></param>
/// <returns>返回json序列</returns>
private string getByList(HttpContext context)
{
//{total:15,rows:[{name:‘test‘,age:12},{name:‘test2‘,age:18}]}
List<Video> video = new List<Video>();
for (int i = 0; i < 3;i++ )
{
video.Add(new Video
{
videoName = "测试",
videoSize = "2M",
videoTime = "70",
videoType = "mp4"
});
}
String jsonTextString = JsonSerializer<List<Video>>(video);

return jsonTextString;

}

反序列化一样。将json数据调用即可。

C# json序列化

标签:

原文地址:http://www.cnblogs.com/ybwyf/p/5466455.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!