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. Python日志库logging总结-可能是目前为止将logging库总结的最好的一篇文章

    在部署项目时,不可能直接将所有的信息都输出到控制台中,我们可以将这些信息记录到日志文件中,这样不仅方便我们查看程序运行时的情况,也可以在项目出现故障时根据运行时产生的日志快速定位问题出现的位置. 1. ...

  2. 设备树中指定的中断触发方式与request_irq中指定的触发方式不一致时,内核会使用哪种中断触发方式呢?

    答:会使用request_irq中指定的触发方式

  3. java模拟post进行文件提交 采用httpClient方法

    package com.jd.vd.manage.util.filemultipart; import java.io.BufferedReader;import java.io.File;impor ...

  4. SQL-W3School-函数:SQL GROUP BY 语句

    ylbtech-SQL-W3School-函数:SQL GROUP BY 语句 1.返回顶部 1. 合计函数 (比如 SUM) 常常需要添加 GROUP BY 语句. GROUP BY 语句 GROU ...

  5. MySQL中表的复制以及大型数据表的备份教程

    MySQL中表的复制以及大型数据表的备份教程     这篇文章主要介绍了MySQL中表的复制以及大型数据表的备份教程,其中大表备份是采用添加触发器增量备份的方法,需要的朋友可以参考下 表复制 mysq ...

  6. thymeleaf中switch case多出一个空行

    以下是<thymeleaf3.0.5中文参考手册.pdf>中的代码,官方代码没有具体去查询. <div th:switch="${user.role}"> ...

  7. (八)利用apache组件进行文件上传下载

    一.文件上传 文件上传,即服务器端得到并处理用户上传的文件,这个文件存放在request里,也就是需要对request进行处理. 1.1 编写html文件 <!DOCTYPE html> ...

  8. pycharm重命名文件

    先右键要重命名的文件,然后按照下图操作:

  9. 利用socket编程在ESP32上搭建一个TCP客户端

    通过之前http://www.cnblogs.com/noticeable/p/7636582.html中对socket的编程,已经可以知道如何通过socket编程搭建服务器和客户端了,现在,就在ES ...

  10. 关于cookies、sessionStorage和localStorage解释及区别

    在浏览器查看 HTML4的本地存储 cookie 浏览器的缓存机制提供了可以将用户数据存储在客户端上的方式,可以利用cookie,session等跟服务端进行数据交互. 一.cookie和sessio ...