Skip to content

Instantly share code, notes, and snippets.

@xiaoyvr
Created January 11, 2019 23:26
Show Gist options
  • Save xiaoyvr/9933e1c02a9baec7c6c251c95aa9870e to your computer and use it in GitHub Desktop.
Save xiaoyvr/9933e1c02a9baec7c6c251c95aa9870e to your computer and use it in GitHub Desktop.
using System;
using System.Data;
using Newtonsoft.Json;
using NHibernate;
using NHibernate.SqlTypes;
using NHibernate.UserTypes;
namespace SomeNamespace
{
[Serializable]
public class JsonBlobbed<T> : IUserType where T : class
{
private JsonSerializerSettings settings;
private JsonSerializerSettings Settings
{
get
{
if (settings != null) return settings;
settings = new JsonSerializerSettings
{
ContractResolver = new AutoPropertyAndFieldResolver()
};
CustomizeSettings(settings);
return settings;
}
}
public new bool Equals(object x, object y)
{
if (x == null && y == null)
return true;
if (x == null || y == null)
return false;
var xdocX = Newtonsoft.Json.JsonConvert.SerializeObject(x, Formatting.None, Settings);
var xdocY = Newtonsoft.Json.JsonConvert.SerializeObject(y, Formatting.None, Settings);
return xdocY == xdocX;
}
public int GetHashCode(object x)
{
return x?.GetHashCode() ?? 0;
}
public virtual object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var val = (string)NHibernateUtil.String.NullSafeGet(rs, names[0]);
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(val, Settings);
}
public virtual void NullSafeSet(IDbCommand cmd, object value, int index)
{
var obj = (T)value;
NHibernateUtil.String.NullSafeSet(cmd, Newtonsoft.Json.JsonConvert.SerializeObject(obj, Formatting.None, Settings), index);
}
public virtual object DeepCopy(object value)
{
if (value == null)
return null;
var serialized = Newtonsoft.Json.JsonConvert.SerializeObject(value, Settings);
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(serialized, Settings);
}
public object Replace(object original, object target, object owner)
{
return original;
}
public object Assemble(object cached, object owner)
{
return string.IsNullOrWhiteSpace(cached as string) ? null : Newtonsoft.Json.JsonConvert.DeserializeObject<T>((string)cached, Settings);
}
public object Disassemble(object value)
{
return value == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(value, Formatting.None, Settings);
}
public SqlType[] SqlTypes => new SqlType[] { new StringClobSqlType() };
public virtual Type ReturnedType => typeof(T);
public bool IsMutable => true;
protected virtual void CustomizeSettings(JsonSerializerSettings jsonSerializerSettings)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment