JsonHelper
文章目录
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Globalization;
using System.IO;
#if !SILVERLIGHT
#endif
namespace GT.Common.JsonHelper
{
public delegate string Serialize(object data);
public delegate object Deserialize(string data);
public sealed class JSONParameters
{
///
/// Use the optimized fast Dataset Schema format (default = True)
///
public bool UseOptimizedDatasetSchema = true;
///
/// Use the fast GUID format (default = True)
///
public bool UseFastGuid = false;
///
/// Serialize null values to the output (default = True)
///
public bool SerializeNullValues = true;
///
/// 是否采用严格的ISO日期 (default = false) by itdos.com
///
public bool UseStrictIsoDate = false;
///
/// 日期格式化 (default = "yyyy-MM-dd HH:mm:ss") by itdos.com
///
public string DateFormatString = "yyyy-MM-dd HH:mm:ss";
///
/// IsLiteral=false时是否序列化。(default = false)
///
public bool UseFalseLiteral = false;
///
/// Use the UTC date format (default = True)
///
public bool UseUTCDateTime = false;
///
/// Show the readonly properties of types in the output (default = False)
///
public bool ShowReadOnlyProperties = true;
///
/// Use the $types extension to optimise the output json (default = True)
///
public bool UsingGlobalTypes = false;
///
/// Ignore case when processing json and deserializing
///
[Obsolete("Not needed anymore and will always match")]
public bool IgnoreCaseOnDeserialize = false;
///
/// Anonymous types have read only properties
///
public bool EnableAnonymousTypes = false;
///
/// Enable fastJSON extensions $types, $type, $map (default = True)
///
public bool UseExtensions = false;
///
/// Use escaped unicode i.e. \uXXXX format for non ASCII characters (default = True)
///
public bool UseEscapedUnicode = false;
///
/// Output string key dictionaries as "k"/"v" format (default = False)
///
public bool KVStyleStringDictionary = false;
///
/// Output Enum values instead of names (default = False)
///
public bool UseValuesOfEnums = false;
///
/// Ignore attributes to check for (default : XmlIgnoreAttribute)
///
public List IgnoreAttributes = new List { typeof(System.Xml.Serialization.XmlIgnoreAttribute) };
///
/// If you have parametric and no default constructor for you classes (default = False)
///
/// IMPORTANT NOTE : If True then all initial values within the class will be ignored and will be not set
///
public bool ParametricConstructorOverride = false;
///
/// 是否序列化DateTime毫秒。 yyyy-MM-dd HH:mm:ss.nnn (default = false)
///
public bool DateTimeMilliseconds = false;
///
/// Maximum depth for circular references in inline mode (default = 20)
///
public byte SerializerMaxDepth = 20;
///
/// Inline circular or already seen objects instead of replacement with $i (default = False)
///
public bool InlineCircularReferences = false;
///
/// Save property/field names as lowercase (default = false)
///
public bool SerializeToLowerCaseNames = false;
///
/// DataTable类型是否默认序列化TableName (default = true) by itdos.com
///
public bool DataTableToGeneralJson = true;
public void FixValues()
{
if (UseExtensions == false) // disable conflicting params
{
UsingGlobalTypes = false;
InlineCircularReferences = true;
}
if (EnableAnonymousTypes)
ShowReadOnlyProperties = true;
}
}
public static class JSON
{
///
/// Globally set-able parameters for controlling the serializer
///
public static JSONParameters Parameters = new JSONParameters();
///
/// Create a formatted json string (beautified) from an object
///
///
///
///
public static string ToNiceJSON(object obj, JSONParameters param)
{
string s = ToJSON(obj, param);
return Beautify(s);
}
///
/// Create a json representation for an object
///
///
///
public static string ToJSON(object obj)
{
return ToJSON(obj, JSON.Parameters);
}
///
/// Create a json representation for an object with parameter override on this call
///
///
///
///
public static string ToJSON(object obj, JSONParameters param)
{
param.FixValues();
Type t = null;
if (obj == null)
return "null";
if (obj.GetType().IsGenericType)
t = Reflection.Instance.GetGenericTypeDefinition(obj.GetType());
if (t == typeof(Dictionary<,>) || t == typeof(List<>))
param.UsingGlobalTypes = false;
// FEATURE : enable extensions when you can deserialize anon types
if (param.EnableAnonymousTypes) { param.UseExtensions = false; param.UsingGlobalTypes = false; }
return new JSONSerializer(param).ConvertToJSON(obj);
}
///
/// Parse a json string and generate a Dictionary<string,object> or List<object> structure
///
///
///
public static object Parse(string json)
{
return new JsonParser(json).Decode();
}
#if net4
///
/// Create a .net4 dynamic object from the json string
///
///
///
public static dynamic ToDynamic(string json)
{
return new DynamicJson(json);
}
#endif
///
/// Create a typed generic object from the json
///
///
///
///
public static T ToObject(string json)
{
return new deserializer(Parameters).ToObject(json);
}
///
/// Create a typed generic object from the json with parameter override on this call
///
///
///
///
///
public static T ToObject(string json, JSONParameters param)
{
return new deserializer(param).ToObject(json);
}
///
/// Create an object from the json
///
///
///
public static object ToObject(string json)
{
return new deserializer(Parameters).ToObject(json, null);
}
///
/// Create an object from the json with parameter override on this call
///
///
///
///
public static object ToObject(string json, JSONParameters param)
{
return new deserializer(param).ToObject(json, null);
}
///
/// Create an object of type from the json
///
///
///
///
public static object ToObject(string json, Type type)
{
return new deserializer(Parameters).ToObject(json, type);
}
///
/// Fill a given object with the json represenation
///
///
///
///
public static object FillObject(object input, string json)
{
Dictionary<string, object> ht = new JsonParser(json).Decode() as Dictionary<string, object>;
if (ht == null) return null;
return new deserializer(Parameters).ParseDictionary(ht, null, input.GetType(), input);
}
///
/// Deep copy an object i.e. clone to a new object
///
///
///
public static object DeepCopy(object obj)
{
return new deserializer(Parameters).ToObject(ToJSON(obj));
}
///
///
///
///
///
///
public static T DeepCopy(T obj)
{
return new deserializer(Parameters).ToObject(ToJSON(obj));
}
///
/// Create a human readable string from the json
///
///
///
public static string Beautify(string input)
{
return Formatter.PrettyPrint(input);
}
///
/// Register custom type handlers for your own types not natively handled by fastJSON
///
///
///
///
public static void RegisterCustomType(Type type, Serialize serializer, Deserialize deserializer)
{
Reflection.Instance.RegisterCustomType(type, serializer, deserializer);
}
///
/// Clear the internal reflection cache so you can start from new (you will loose performance)
///
public static void ClearReflectionCache()
{
Reflection.Instance.ClearReflectionCache();
}
internal static long CreateLong(out long num, string s, int index, int count)
{
num = 0;
bool neg = false;
for (int x = 0; x < count; x++, index++)
{
char cc = s[index];
if (cc == '-')
neg = true;
else if (cc == '+')
neg = false;
else
{
num *= 10;
num += (int)(cc - '0');
}
}
if (neg) num = -num;
return num;
}
}
internal class deserializer
{
public deserializer(JSONParameters param)
{
_params = param;
}
private JSONParameters _params;
private bool _usingglobals = false;
private Dictionary<object, int> _circobj = new Dictionary<object, int>();
private Dictionary<int, object> _cirrev = new Dictionary<int, object>();
public T ToObject(string json)
{
Type t = typeof(T);
var o = ToObject(json, t);
if (t.IsArray)
{
if ((o as ICollection).Count == 0) // edge case for "[]" -> T[]
{
Type tt = t.GetElementType();
object oo = Array.CreateInstance(tt, 0);
return (T)oo;
}
else
return (T)o;
}
else
return (T)o;
}
public object ToObject(string json)
{
return ToObject(json, null);
}
public object ToObject(string json, Type type)
{
//_params = Parameters;
_params.FixValues();
Type t = null;
if (type != null && type.IsGenericType)
t = Reflection.Instance.GetGenericTypeDefinition(type);
if (t == typeof(Dictionary<,>) || t == typeof(List<>))
_params.UsingGlobalTypes = false;
_usingglobals = _params.UsingGlobalTypes;
object o = new JsonParser(json).Decode();
if (o == null)
return null;
#if !SILVERLIGHT
if (type != null && type == typeof(DataSet))
return CreateDataset(o as Dictionary<string, object>, null);
else if (type != null && type == typeof(DataTable))
return CreateDataTable(o, null);// by itdos.com
#endif
if (o is IDictionary)
{
if (type != null && t == typeof(Dictionary<,>)) // deserialize a dictionary
return RootDictionary(o, type);
else // deserialize an object
return ParseDictionary(o as Dictionary<string, object>, null, type, null);
}
else if (o is List
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论