using System;
using Newtonsoft.Json;
namespace Abp.Json
{
///
/// Defines helper methods to work with JSON.
///
public static class JsonSerializationHelper
{
private const char TypeSeperator = '|';
///
/// Serializes an object with a type information included.
/// So, it can be deserialized using method later.
///
public static string SerializeWithType(object obj)
{
return SerializeWithType(obj, obj.GetType());
}
///
/// Serializes an object with a type information included.
/// So, it can be deserialized using method later.
///
public static string SerializeWithType(object obj, Type type)
{
var serialized = obj.ToJsonString();
return string.Format(
"{0}{1}{2}",
type.AssemblyQualifiedName,
TypeSeperator,
serialized
);
}
///
/// Deserializes an object serialized with methods.
///
public static T DeserializeWithType(string serializedObj)
{
return (T)DeserializeWithType(serializedObj);
}
///
/// Deserializes an object serialized with methods.
///
public static object DeserializeWithType(string serializedObj)
{
var typeSeperatorIndex = serializedObj.IndexOf(TypeSeperator);
var type = Type.GetType(serializedObj.Substring(0, typeSeperatorIndex));
var serialized = serializedObj.Substring(typeSeperatorIndex + 1);
var options = new JsonSerializerSettings
{
ContractResolver = new AbpCamelCasePropertyNamesContractResolver()
};
return JsonConvert.DeserializeObject(serialized, type, options);
}
}
}