使⽤Newtonsoft.Json序列化和反序列化对象(源码)
  Json数据格式,简单⽽强⼤。
  使⽤Json,不得不提到Newtonsoft.Json,它帮助我们更⽅便的使⽤Json,当然,不使⽤它也是可以的,还有许多⽅法将对象序列化成Json字符串,暂且不提。
  我使⽤Json主要是在两个⽅⾯:
  第⼀,在后台代码,⽤JsonConvert.SerializeObject()⽅法将对象序列化成字符串对象,然后在前台代码中,再⽤Json.Parse()⽅法反序列成javascript对象,然后处理对象;这种情况往往是在读数据库时会需要的,例如,列表页⾯;
  第⼆,在前台代码,将javascript对象利⽤Json.stringify()⽅法序列化成字符串,然后传输到,后台代码中,再⽤
JsonConvert.DeserializeObject<T>()⽅法反序列化成对象,然后处理对象;这种情况往往是在往数据库增加或者修改数据时需要的,例如,增加页⾯;
  在这个过程中,需要注意的是:
  1、在后台定义的对象与前台定义的对象,名称要相同,⼤⼩可以不⼀样;
  另外需要啰嗦两句的是,我写的⽰例功能都是从公司的项⽬中,抽出来的⼀点功能点,然后⽤⾃⼰的想法来操作实现的,通过这样的练习,才可以慢慢地提⾼⾃⼰;另外,每个练习都是认真的按照⼤项⽬的编码规范去做的,例如,项⽬命名规范;编辑命名规范等等。
  本⽰例主要是实现了上⾯两个⽅法:显⽰数据和保存数据,注意没有连接数据库,只是传输⼀下数据⽽已。
  好吧,下⾯就不废话,贴上代码说明问题:
  CodeSetupEdit.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CodeSetupEdit.aspx.cs" Inherits="CodeSetup.CodeSetupEdit" %>
<!DOCTYPE html>
<html xmlns="/1999/xhtml">
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="js/jquery-1.9.1.js"></script>
<script src="js/ajaxhelper.js"></script>
<script>
$(document).ready(function () {
ajaxmethod("../Handler/CodeSetupHandler.ashx?actiontype=getlist", function (data) {
var obj = JSON.parse(data);
$("#txtContext").val("编码选项是:" + obj.CodeOption + ";占位符是:" + obj.PlaceHolder + ";长度是:" + obj.Length + ";是否连号:" + obj.IsNeedContinuous);            });
});
var CodeSetup = function (codeoption, placeholder, length, isneedcontinuous) {
this.CodeOption = codeoption,
this.PlaceHolder = placeholder,
this.Length = length,
this.IsNeedContinuous = isneedcontinuous
}
function save() {
var url = "../Handler/CodeSetupHandler.ashx?actiontype=save";
var codesetupEntity = new CodeSetup(1, "yyyy", 3, 1);
$.post(url,
{
CodeSetupEntity: JSON.stringify(codesetupEntity),
}, function (data) {
}, "text");
}jquery源码在线
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<textarea id="txtContext" ></textarea>
<input type="button" id="btnSave" value="保存" onclick="save()" />
</div>
</form>
</body>
</html>
  CodeSetupHandler.ashx
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CodeSetup.Handler
{
///<summary>
/// CodeSetupHandler 的摘要说明
///</summary>
public class CodeSetupHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string action = context.Request["actiontype"] ?? context.Request["actiontype"].ToString();
switch (action)
{
case"getlist":
context.Response.Write(GetModel());
break;
case"save":
Save();
break;
default:
break;
}
}
public string GetModel()
{
var codeSetup = new CodeSetup()
{
CodeOption = (int)CodeOptionType.Date,
IsNeedContinuous = 0,
Length = 0,
placeHolder = ((int)DateType.YYYYMMDD).ToString()
};
return JsonConvert.SerializeObject(codeSetup);
}
public void Save()
{
string codesetupentity = HttpContext.Current.Request.Form["CodeSetupEntity"];
JObject o = JObject.Parse(codesetupentity.ToString());
//string codeoption = o["CodeOption"].ToString();
//string placeholder = o["PlaceHolder"].ToString();
//string length = o["Length"].ToString();
//string isneedcontinuous = o["IsNeedContinuous"].ToString();
CodeSetup codeSetup = JsonConvert.DeserializeObject<CodeSetup>(codesetupentity);        }
public bool IsReusable
{
get
{
return false;
}
}
}
public class CodeSetup
{
public int CodeOption { get; set; }
public string placeHolder { get; set; }
public int Length { get; set; }
public int IsNeedContinuous { get; set; }
}
public enum CodeOptionType
{
///<summary>
///⾃定义
///</summary>
[Description("⾃定义")]
Define = 0,
/
//<summary>
///⽇期
///</summary>
[Description("⽇期")]
Date = 1,
///<summary>
///分隔符
///</summary>
[Description("分隔符")]
Separator = 2,
///<summary>
/
//流⽔号
///</summary>
[Description("流⽔号")]
Number = 3,
}
public enum DateType
{
///<summary>
///年⽉⽇
///</summary>
[Description("年⽉⽇")]
YYYYMMDD = 0,
///<summary>
///年⽉
///</summary>
[Description("年⽉")]
YYYYMM = 1,
///<summary>
///年
///</summary>
[Description("年")]
YYYY = 2,
/
//<summary>
///⽉
///</summary>
[Description("⽉")]
MM = 3,
///<summary>
///⽇
///</summary>
[Description("⽇")]
DD = 3,
}
public enum SeparatorType
{
///<summary>
/// _
///</summary>
[Description("下划线")]
Underline = 0,
///<summary>
/// -
///</summary>
[Description("短横线")]
Hyphen = 1,
}
///<summary>
///枚举⼯具类
///</summary>
public sealed class EnumUtil
{
private static Dictionary<string, Dictionary<int, string>> _EnumList = new Dictionary<string, Dictionary<int, string>>(); //枚举缓存池///<summary>
///将枚举绑定到ListControl
///</summary>
///<param name="listControl">ListControl</param>
///<param name="enumType">枚举类型</param>
public static void FillListControl(ListControl listControl, Type enumType)
{
listControl.Items.Clear();
listControl.DataSource = EnumToDictionary(enumType);
listControl.DataValueField = "key";
listControl.DataTextField = "value";
listControl.DataBind();
}
///<summary>
///将枚举转换成Dictionary<int, string>
/
// Dictionary中,key为枚举项对应的int值;value为:若定义了EnumShowName属性,则取它,否则取name
///</summary>
///<param name="enumType">枚举类型</param>
///<returns></returns>
public static Dictionary<int, string> EnumToDictionary(Type enumType)
{
string keyName = enumType.FullName;
if (!_EnumList.ContainsKey(keyName))
{
Dictionary<int, string> list = new Dictionary<int, string>();
foreach (int i in Enum.GetValues(enumType))
{
string name = Enum.GetName(enumType, i);
//取显⽰名称
string showName = string.Empty;
object[] atts = enumType.GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false);
if (atts.Length > 0) showName = ((DescriptionAttribute)atts[0]).Description;
list.Add(i, string.IsNullOrEmpty(showName) ? name : showName);
}
object syncObj = new object();
if (!_EnumList.ContainsKey(keyName))
{
lock (syncObj)
{
if (!_EnumList.ContainsKey(keyName))
{
_EnumList.Add(keyName, list);
}
}
}
}
return _EnumList[keyName];
}
/
//<summary>
///获取枚举值对应的显⽰名称
///</summary>
///<param name="enumType">枚举类型</param>
///<param name="intValue">枚举项对应的int值</param>
///<returns></returns>
public static string GetDescription(Type enumType, int intValue)
{
return EnumToDictionary(enumType)[intValue];
}
}
}
  贴完代码后,才发现⾥⾯还有⼏段代码与写的这个⽰例是不相关的,主要是枚举的⼀个⼯具类,这个⼤家可以忽略就⾏。 

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。