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 ...
随机推荐
- linux 之oracle静默安装
一.安装前准备工作1.修改主机名#vi /etc/hosts //并添加内网IP地址对应的hostname,如下127.0.0.1 localhost::1 ...
- 【转】nodejs接收前端formData数据
很多时候需要利用formdata数据格式进行前后端交互. 前端代码可以是如下所示: <!DOCTYPE html> <html lang="en"> < ...
- android studio: 9:57 Unsupported Modules Detected: Compilation is not supported for following modules: map, app, ota, MediaEditor, rcLcmSercive, DroneSDK, qrcodelibrary, rcService, speechService. Unfo
Android studio Error “Unsupported Modules Detected: Compilation is not supported for following modul ...
- js求数组最大值方法
定义数组 var arr = [-1, 1, 101, -52, 10, 1001, 1001] 1.es6拓展运算符... Math.max(...arr) 2.es5 apply(与方法1原理相同 ...
- 【转载】 一文看懂深度学习新王者「AutoML」:是什么、怎么用、未来如何发展?
原文地址: http://www.sohu.com/a/249973402_610300 原作:George Seif 夏乙 安妮 编译整理 ============================= ...
- 123457123456#0#-----com.threeapp.renZheDadishu02-----忍者版打地鼠
com.threeapp.renZheDadishu02-----忍者版打地鼠
- PAT 甲级 1060 Are They Equal (25 分)(科学计数法,接连做了2天,考虑要全面,坑点多,真麻烦)
1060 Are They Equal (25 分) If a machine can save only 3 significant digits, the float numbers 1230 ...
- LeetCode_83. Remove Duplicates from Sorted List
83. Remove Duplicates from Sorted List Easy Given a sorted linked list, delete all duplicates such t ...
- 更新Conda源和pip源
更新conda源 各系统都可以通过修改用户目录下的 .condarc 文件: channels: - defaults show_channel_urls: true default_channels ...
- iOS面试考察点
)自我介绍.项目经历.专业知识.自由提问 (2)准备简历.投发简历.笔试(电话面试.).面试.复试.终面试.试用.转正.发展.跳槽(加薪升职) 1闲聊 a)自我介绍:自我认识能力 b)评价上一家公司: ...