/// <summary>
/// Serializes an object to an XML string. Unlike the other SerializeObject overloads
/// this methods *returns a string* rather than a bool result!
/// </summary>
/// <param name="value">Value to serialize</param>
/// <param name="throwExceptions">Determines if a failure throws or returns null</param>
/// <returns>
/// null on error otherwise the Xml String.
/// </returns>
/// <remarks>
/// If null is passed in null is also returned so you might want
/// to check for null before calling this method.
/// </remarks>
public static string Serialize(object value, bool throwExceptions = false, bool formatJsonOutput = false)
{
string jsonResult = null;
Type type = value.GetType();
dynamic writer = null;
try
{
var json = new JsonSerializer();
StringWriter sw = new StringWriter();
writer = new Newtonsoft.Json.JsonTextWriter(sw);
if (formatJsonOutput)
{
writer.Formatting = Formatting.Indented;
}
else
{
writer.Formatting = Formatting.None;
}
writer.QuoteChar = '"';
json.Serialize(writer, value);
jsonResult = sw.ToString();
writer.Close();
}
catch (Exception ex)
{
if (throwExceptions)
{
throw ex;
}
jsonResult = null;
}
finally
{
if (writer != null)
{
writer.Close();
}
}
return(jsonResult);
}