JSON序列化必看以及序列化工具类
1、要序列化的类必须用 [DataContract] 特性标识
// /*---------------
// // 使用地方: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序列化必看以及序列化工具类的更多相关文章
- Json与javaBean之间的转换工具类
/** * Json与javaBean之间的转换工具类 * * {@code 现使用json-lib组件实现 * 需要 * json-lib-2.4-jdk15.jar * ...
- 自写Date工具类
以前写项目的时候总是在使用到了时间的转换的时候才在工具类中添加一个方法,这样很容易导致代码冗余以及转换的方法注释不清晰导致每次使用都要重新看一遍工具类.因此整理出经常使用的一些转换,用作记录,以便以后 ...
- Android PermissionUtils:运行时权限工具类及申请权限的正确姿势
Android PermissionUtils:运行时权限工具类及申请权限的正确姿势 ifadai 关注 2017.06.16 16:22* 字数 318 阅读 3637评论 1喜欢 6 Permis ...
- Gson手动序列化POJO(工具类)
gson2.7版本 只是简单的工具类(练习所用): package pojo; import javax.xml.bind.annotation.XmlSeeAlso; import com.goog ...
- 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 ...
- 使用Json.Net处理json序列化和反序列化接口或继承类
以前一直没有怎么关注过Newtonsoft的Json.Net这个第三方的.NET Json框架,主要是我以前在开发项目的时候大多数使用的都是.NET自带的Json序列化类JavaScriptSeria ...
- redis缓存工具类,提供序列化接口
1.序列化工具类 package com.qicheshetuan.backend.util; import java.io.ByteArrayInputStream; import java.io. ...
- Java 序列化工具类
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sun.misc.BASE64Decoder; import sun.m ...
- Java 序列化对象工具类
SerializationUtils.java package javax.utils; import java.io.ByteArrayInputStream; import java.io.Byt ...
随机推荐
- arcgis python ValueTable使用
本文链接:https://blog.csdn.net/A873054267/article/details/86007125 #多值参数指定方式 1 python list类型 2 字符串类型,以逗号 ...
- CSRF in asp.net mvc and ap.net core
如果在方法上添加了[ValidateAntiForgeryToken],没处理好 请求没有带参数 2019-09-17 14:02:45,142 ERROR [36]: System.Web.Mvc. ...
- 【Python】把文件名命名成canlendar.py竟然导致无法使用canlendar模块 附赠2020年月历
这个bug困扰了我一阵,直到在 http://www.codingke.com/question/15489 找到了解决问题的钥匙,真是没想到居然是这个原因导致的. 下面是出错信息,可以看到只要目录下 ...
- spark "main" java.lang.ArrayIndexOutOfBoundsException: 10582
升级 你的 paranamer 到2.8 ,这是由于你的jdk版本1.8导致 <!-- https://mvnrepository.com/artifact/com.thoughtworks.p ...
- Linux输出信息并将信息记录到文件(tee命令)
摘自:https://www.jb51.net/article/104846.htm 前言 最近工作中遇到一个需求,需要将程序的输出写到终端,同时写入文件,通过查找相关的资料,发现可以用 tee 命令 ...
- java 利用poi 实现excel合并单元格后出现边框有的消失的解决方法
使用工具类RegionUtil CellRangeAddress cra = new CellRangeAddress(nowRowCount, nowRowCount + followSize-1, ...
- 激活Microsoft Word 2010
先关闭系统的防火墙(像360安全卫士这类软件),再运行“office 2010 正版验证激活工具”,并点击“Install/Uninstall KMService”安装“KMS”服务器(如下图,在弹出 ...
- thymeleaf中double/float格式化,四舍五入显示两位小数
private Float balance; 代码: <span class="A124_balance_num" th:text="${#numbers.form ...
- kubenetes安装
master节点主要由四个模块组成: APIServer 提供了资源操作的唯一入口,任何对资源进行增删改查的操作都要交给APIServer处理后再提交给etcd.kubectl就是对api ser ...
- 【创业】2B创业历程
http://www.woshipm.com/chuangye/2800111.html http://www.woshipm.com/chuangye/2803240.html http://www ...