1、要序列化的类必须用 [DataContract] 特性标识

 
2、需要序列化的属性应用 [DataMember] 特性标识,没有该特性则表示不序列化该属性。类亦如此!
 
3、可以网络上找封装好的序列化类工具,也可以引用 System.json 程序集
 
 // /*---------------
// // 使用地方:eKing 警备系统 【终端和服务器之间的数据同步】
// //
// // 文件名:JsonUtils.cs
// // 文件功能描述:
// // 指定对象序列化成JSON
// // 将JSON反序列化成原对象
// // JsonUtils.Serialize(result); --- Serialize() 方法支持序列化(对象嵌套对象)的需求
// // 可直接调用Serialize()方法,可同时序列化指定对象包含的自定义对象,甚至List集合
// //
// // 创建标识:米立林20140319
// //
// // 修改标识:
// // 修改描述:
// //----------------------------------------------------------------*/
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web.Script.Serialization;
namespace BJJDKJ.PEDIMS.SyncService
{
public class JsonUtils
{
// Methods
public static T Deserialize<T>(string json)
{
//将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式
string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
Regex reg = new Regex(p);
json = reg.Replace(json, matchEvaluator);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return (T)serializer.ReadObject(stream);
}
}
public static Dictionary<string, object> DeserializeDictionaryToJson(string json)
{
Dictionary<string, object> dictionary2;
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new Collection<JavaScriptConverter>());
dictionary2 = serializer.Deserialize<Dictionary<string, object>>(json);
return dictionary2;
}
public static T DeserializeEntityByBase64<T>(string json)
{
List<T> list = DeserializeListByBase64<T>(json);
if ((list != null) && (list.Count > ))
{
return list[];
}
T local = Deserialize<T>(json);
if (local != null)
{
PropertyInfo[] properties = local.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
foreach (PropertyInfo info in properties)
{
if (info.PropertyType == typeof(string))
{
object obj2 = info.GetValue(local, null);
if (obj2 != null)
{
//info.SetValue(local, ConvertUtils.ConvertFromBase64String(obj2.ToString()), null);
info.SetValue(local, obj2.ToString(), null);
}
}
}
return local;
}
return default(T);
}
public static List<T> DeserializeListByBase64<T>(string json)
{
List<T> list = Deserialize<List<T>>(json);
if ((list != null) && (list.Count > ))
{
foreach (T local in list)
{
PropertyInfo[] properties = local.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
foreach (PropertyInfo info in properties)
{
if (info.PropertyType == typeof(string))
{
object obj2 = info.GetValue(local, null);
if (obj2 != null)
{
info.SetValue(local, ConvertUtils.ConvertFromBase64String(obj2.ToString()), null);
}
}
}
}
}
return list;
}
public static string Serialize<T>(T data)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(data.GetType());
using (MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, data);
string jsonStr = Encoding.UTF8.GetString(stream.ToArray());
//替换Json的Date字符串
//string p = @"/\//Date/((/d+)/+/d+/)/\//";
/*////Date/((([/+/-]/d+)|(/d+))[/+/-]/d+/)////*/
string p = @"\\/Date\((\d+)\+\d+\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(p);
jsonStr = reg.Replace(jsonStr, matchEvaluator);
return jsonStr;
}
}
public static string SerializeEntityByBase64<T>(T t)
{
List<T> list = new List<T> { t };
return SerializeListByBase64(list);
}
public static string SerializeJsonToDictionary(Dictionary<string, object> dic)
{
string str2;
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new Collection<JavaScriptConverter>());
str2 = serializer.Serialize(dic);
return str2;
}
public static string SerializeListByBase64<T>(List<T> list)
{
if ((list != null) && (list.Count > ))
{
foreach (T local in list)
{
PropertyInfo[] properties = local.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
foreach (PropertyInfo info in properties)
{
if (info.PropertyType == typeof(string))
{
if (info.Name == "SIM_Police")
{
}
object obj2 = info.GetValue(local, null);
if (obj2 != null)
{
info.SetValue(local, ConvertUtils.ConvertToBase64String(obj2.ToString()), null);
}
}
}
}
return Serialize(list);
}
return "";
}
private static string WipeSpecialChar(string str)
{
StringBuilder builder = new StringBuilder();
for (int i = ; i < str.Length; i++)
{
char ch = str.ElementAt(i);
char ch2 = ch;
if (ch2 <= '\'')
{
switch (ch2)
{
case '\b':
{
builder.Append(@"\b");
continue;
}
case '\t':
{
builder.Append(@"\t");
continue;
}
case '\n':
{
builder.Append(@"\n");
continue;
}
case '\v':
goto Label_00C7;
case '\f':
{
builder.Append(@"\f");
continue;
}
case '\r':
{
builder.Append(@"\r");
continue;
}
case '\'':
goto Label_00B9;
}
goto Label_00C7;
}
if (ch2 != '/')
{
if (ch2 != '\\')
{
goto Label_00C7;
}
builder.Append(@"\\");
}
else
{
builder.Append(@"\/");
}
continue;
Label_00B9:
builder.Append(@"\'");
continue;
Label_00C7:
builder.Append(ch);
}
return builder.ToString();
}
/// <summary>
/// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串
/// </summary>
private static string ConvertJsonDateToDateString(Match m)
{
string result = string.Empty;
DateTime dt = new DateTime(, , );
dt = dt.AddMilliseconds(long.Parse(m.Groups[].Value));
dt = dt.ToLocalTime();
result = dt.ToString("yyyy-MM-dd HH:mm:ss");
return result;
}
/// <summary>
/// 将时间字符串转为Json时间
/// </summary>
private static string ConvertDateStringToJsonDate(Match m)
{
string result = string.Empty;
DateTime dt = DateTime.Parse(m.Groups[].Value);
dt = dt.ToUniversalTime();
TimeSpan ts = dt - DateTime.Parse("1970-01-01");
result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
return result;
}
}
}

JSON序列化必看以及序列化工具类的更多相关文章

  1. Json与javaBean之间的转换工具类

    /**  * Json与javaBean之间的转换工具类  *  * {@code 现使用json-lib组件实现  *    需要  *     json-lib-2.4-jdk15.jar  * ...

  2. 自写Date工具类

    以前写项目的时候总是在使用到了时间的转换的时候才在工具类中添加一个方法,这样很容易导致代码冗余以及转换的方法注释不清晰导致每次使用都要重新看一遍工具类.因此整理出经常使用的一些转换,用作记录,以便以后 ...

  3. Android PermissionUtils:运行时权限工具类及申请权限的正确姿势

    Android PermissionUtils:运行时权限工具类及申请权限的正确姿势 ifadai 关注 2017.06.16 16:22* 字数 318 阅读 3637评论 1喜欢 6 Permis ...

  4. Gson手动序列化POJO(工具类)

    gson2.7版本 只是简单的工具类(练习所用): package pojo; import javax.xml.bind.annotation.XmlSeeAlso; import com.goog ...

  5. c#中@标志的作用 C#通过序列化实现深表复制 细说并发编程-TPL 大数据量下DataTable To List效率对比 【转载】C#工具类:实现文件操作File的工具类 异步多线程 Async .net 多线程 Thread ThreadPool Task .Net 反射学习

    c#中@标志的作用   参考微软官方文档-特殊字符@,地址 https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/toke ...

  6. 使用Json.Net处理json序列化和反序列化接口或继承类

    以前一直没有怎么关注过Newtonsoft的Json.Net这个第三方的.NET Json框架,主要是我以前在开发项目的时候大多数使用的都是.NET自带的Json序列化类JavaScriptSeria ...

  7. redis缓存工具类,提供序列化接口

    1.序列化工具类 package com.qicheshetuan.backend.util; import java.io.ByteArrayInputStream; import java.io. ...

  8. Java 序列化工具类

    import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sun.misc.BASE64Decoder; import sun.m ...

  9. Java 序列化对象工具类

    SerializationUtils.java package javax.utils; import java.io.ByteArrayInputStream; import java.io.Byt ...

随机推荐

  1. OpenJudge计算概论-成绩判断

    /*========================================================= 成绩判断 总时间限制: 1000ms 内存限制: 6000kB 描述 输入一个0 ...

  2. SOCKET_CONNECT_TIMEOUT is the timeout for the connection to be established and SOCKET_TIMEOUT

    https://github.com/niwinz/django-redis/blob/master/doc/content.adoc#32-socket-timeout 3.2. Socket ti ...

  3. 双缓冲技术局部更新原理之派生自SurfaceView

    package com.loaderman.customviewdemo; import android.content.Context; import android.graphics.Canvas ...

  4. QML异常:Cannot anchor to an item that isn't a parent or sibling

    翻译: 无法定位到不是父项或同级项的项 QML的anchor必须定位父级对象或者同级对象,不能定位到其他如:同级对象的子对象

  5. Django中的文件上传和原生Ajax

    概述 Django中的上传有3种方案: form 表单常规上传,但点击提交后会自动刷新页面 Ajax 上传,不刷新页面,(分为原生ajax上传和jQuery上传),IE7以上不兼容 iframe 上传 ...

  6. preg_replace修饰符e的用法

    $tmp_refer = postget('refer');$tmp_refer = preg_replace("/tn-(.*?).html/ies", "'tn-'. ...

  7. 记EXSI虚拟机CentOS7断电无法启动修复过程

    参考:https://msd.misuland.com/pd/3148108429789233656 EXSI6.7安装虚拟机CentOS7.5 1804 断电后启动页面进度条很慢 最后出现如下提示 ...

  8. sonar:windows重启sonar

    登录后操作

  9. 【ARM-Linux开发】Rico Board上编译USB WiFi RT3070驱动

    1.附件中提供了RT3070驱动源码包DPO_RT5572_LinuxSTA_2.6.1.3_20121022.tar.gz和编译好的驱动,这里选择使用taget_file.tar.gz中已经编译好的 ...

  10. jqGrid获取选中行id集合

    $("#jqGrid").jqGrid("getGridParam","selarrrow");