#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.IO;
using System.Globalization;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using LC.Newtonsoft.Json.Linq;
using LC.Newtonsoft.Json.Utilities;
using System.Xml;
using LC.Newtonsoft.Json.Converters;
using LC.Newtonsoft.Json.Serialization;
using System.Text;
using System.Diagnostics;
#if HAVE_XLINQ
using System.Xml.Linq;
#endif
namespace LC.Newtonsoft.Json
{
///
/// Provides methods for converting between .NET types and JSON types.
///
///
///
///
public static class JsonConvert
{
///
/// Gets or sets a function that creates default .
/// Default settings are automatically used by serialization methods on ,
/// and and on .
/// To serialize without using any default settings create a with
/// .
///
public static Func DefaultSettings { get; set; }
///
/// Represents JavaScript's boolean value true as a string. This field is read-only.
///
public static readonly string True = "true";
///
/// Represents JavaScript's boolean value false as a string. This field is read-only.
///
public static readonly string False = "false";
///
/// Represents JavaScript's null as a string. This field is read-only.
///
public static readonly string Null = "null";
///
/// Represents JavaScript's undefined as a string. This field is read-only.
///
public static readonly string Undefined = "undefined";
///
/// Represents JavaScript's positive infinity as a string. This field is read-only.
///
public static readonly string PositiveInfinity = "Infinity";
///
/// Represents JavaScript's negative infinity as a string. This field is read-only.
///
public static readonly string NegativeInfinity = "-Infinity";
///
/// Represents JavaScript's NaN as a string. This field is read-only.
///
public static readonly string NaN = "NaN";
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(DateTime value)
{
return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
}
///
/// Converts the to its JSON string representation using the specified.
///
/// The value to convert.
/// The format the date will be converted to.
/// The time zone handling when the date is converted to a string.
/// A JSON string representation of the .
public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
{
DateTime updatedDateTime = DateTimeUtils.EnsureDateTime(value, timeZoneHandling);
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
writer.Write('"');
DateTimeUtils.WriteDateTimeString(writer, updatedDateTime, format, null, CultureInfo.InvariantCulture);
writer.Write('"');
return writer.ToString();
}
}
#if HAVE_DATE_TIME_OFFSET
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(DateTimeOffset value)
{
return ToString(value, DateFormatHandling.IsoDateFormat);
}
///
/// Converts the to its JSON string representation using the specified.
///
/// The value to convert.
/// The format the date will be converted to.
/// A JSON string representation of the .
public static string ToString(DateTimeOffset value, DateFormatHandling format)
{
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
writer.Write('"');
DateTimeUtils.WriteDateTimeOffsetString(writer, value, format, null, CultureInfo.InvariantCulture);
writer.Write('"');
return writer.ToString();
}
}
#endif
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(bool value)
{
return (value) ? True : False;
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(char value)
{
return ToString(char.ToString(value));
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(Enum value)
{
return value.ToString("D");
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(int value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(short value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
[CLSCompliant(false)]
public static string ToString(ushort value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
[CLSCompliant(false)]
public static string ToString(uint value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(long value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
#if HAVE_BIG_INTEGER
private static string ToStringInternal(BigInteger value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
#endif
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
[CLSCompliant(false)]
public static string ToString(ulong value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(float value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
if (floatFormatHandling == FloatFormatHandling.Symbol || !(double.IsInfinity(value) || double.IsNaN(value)))
{
return text;
}
if (floatFormatHandling == FloatFormatHandling.DefaultValue)
{
return (!nullable) ? "0.0" : Null;
}
return quoteChar + text + quoteChar;
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(double value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
private static string EnsureDecimalPlace(double value, string text)
{
if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1)
{
return text;
}
return text + ".0";
}
private static string EnsureDecimalPlace(string text)
{
if (text.IndexOf('.') != -1)
{
return text;
}
return text + ".0";
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(byte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
[CLSCompliant(false)]
public static string ToString(sbyte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(decimal value)
{
return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(Guid value)
{
return ToString(value, '"');
}
internal static string ToString(Guid value, char quoteChar)
{
string text;
string qc;
#if HAVE_CHAR_TO_STRING_WITH_CULTURE
text = value.ToString("D", CultureInfo.InvariantCulture);
qc = quoteChar.ToString(CultureInfo.InvariantCulture);
#else
text = value.ToString("D");
qc = quoteChar.ToString();
#endif
return qc + text + qc;
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(TimeSpan value)
{
return ToString(value, '"');
}
internal static string ToString(TimeSpan value, char quoteChar)
{
return ToString(value.ToString(), quoteChar);
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(Uri value)
{
if (value == null)
{
return Null;
}
return ToString(value, '"');
}
internal static string ToString(Uri value, char quoteChar)
{
return ToString(value.OriginalString, quoteChar);
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(string value)
{
return ToString(value, '"');
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// The string delimiter character.
/// A JSON string representation of the .
public static string ToString(string value, char delimiter)
{
return ToString(value, delimiter, StringEscapeHandling.Default);
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// The string delimiter character.
/// The string escape handling.
/// A JSON string representation of the .
public static string ToString(string value, char delimiter, StringEscapeHandling stringEscapeHandling)
{
if (delimiter != '"' && delimiter != '\'')
{
throw new ArgumentException("Delimiter must be a single or double quote.", nameof(delimiter));
}
return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, true, stringEscapeHandling);
}
///
/// Converts the to its JSON string representation.
///
/// The value to convert.
/// A JSON string representation of the .
public static string ToString(object value)
{
if (value == null)
{
return Null;
}
PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(value.GetType());
switch (typeCode)
{
case PrimitiveTypeCode.String:
return ToString((string)value);
case PrimitiveTypeCode.Char:
return ToString((char)value);
case PrimitiveTypeCode.Boolean:
return ToString((bool)value);
case PrimitiveTypeCode.SByte:
return ToString((sbyte)value);
case PrimitiveTypeCode.Int16:
return ToString((short)value);
case PrimitiveTypeCode.UInt16:
return ToString((ushort)value);
case PrimitiveTypeCode.Int32:
return ToString((int)value);
case PrimitiveTypeCode.Byte:
return ToString((byte)value);
case PrimitiveTypeCode.UInt32:
return ToString((uint)value);
case PrimitiveTypeCode.Int64:
return ToString((long)value);
case PrimitiveTypeCode.UInt64:
return ToString((ulong)value);
case PrimitiveTypeCode.Single:
return ToString((float)value);
case PrimitiveTypeCode.Double:
return ToString((double)value);
case PrimitiveTypeCode.DateTime:
return ToString((DateTime)value);
case PrimitiveTypeCode.Decimal:
return ToString((decimal)value);
#if HAVE_DB_NULL_TYPE_CODE
case PrimitiveTypeCode.DBNull:
return Null;
#endif
#if HAVE_DATE_TIME_OFFSET
case PrimitiveTypeCode.DateTimeOffset:
return ToString((DateTimeOffset)value);
#endif
case PrimitiveTypeCode.Guid:
return ToString((Guid)value);
case PrimitiveTypeCode.Uri:
return ToString((Uri)value);
case PrimitiveTypeCode.TimeSpan:
return ToString((TimeSpan)value);
#if HAVE_BIG_INTEGER
case PrimitiveTypeCode.BigInteger:
return ToStringInternal((BigInteger)value);
#endif
}
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
#region Serialize
///
/// Serializes the specified object to a JSON string.
///
/// The object to serialize.
/// A JSON string representation of the object.
[DebuggerStepThrough]
public static string SerializeObject(object value)
{
return SerializeObject(value, null, (JsonSerializerSettings)null);
}
///
/// Serializes the specified object to a JSON string using formatting.
///
/// The object to serialize.
/// Indicates how the output should be formatted.
///
/// A JSON string representation of the object.
///
[DebuggerStepThrough]
public static string SerializeObject(object value, Formatting formatting)
{
return SerializeObject(value, formatting, (JsonSerializerSettings)null);
}
///
/// Serializes the specified object to a JSON string using a collection of .
///
/// The object to serialize.
/// A collection of converters used while serializing.
/// A JSON string representation of the object.
[DebuggerStepThrough]
public static string SerializeObject(object value, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return SerializeObject(value, null, settings);
}
///
/// Serializes the specified object to a JSON string using formatting and a collection of .
///
/// The object to serialize.
/// Indicates how the output should be formatted.
/// A collection of converters used while serializing.
/// A JSON string representation of the object.
[DebuggerStepThrough]
public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return SerializeObject(value, null, formatting, settings);
}
///
/// Serializes the specified object to a JSON string using .
///
/// The object to serialize.
/// The used to serialize the object.
/// If this is null, default serialization settings will be used.
///
/// A JSON string representation of the object.
///
[DebuggerStepThrough]
public static string SerializeObject(object value, JsonSerializerSettings settings)
{
return SerializeObject(value, null, settings);
}
///
/// Serializes the specified object to a JSON string using a type, formatting and .
///
/// The object to serialize.
/// The used to serialize the object.
/// If this is null, default serialization settings will be used.
///
/// The type of the value being serialized.
/// This parameter is used when is to write out the type name if the type of the value does not match.
/// Specifying the type is optional.
///
///
/// A JSON string representation of the object.
///
[DebuggerStepThrough]
public static string SerializeObject(object value, Type type, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
return SerializeObjectInternal(value, type, jsonSerializer);
}
///
/// Serializes the specified object to a JSON string using formatting and .
///
/// The object to serialize.
/// Indicates how the output should be formatted.
/// The used to serialize the object.
/// If this is null, default serialization settings will be used.
///
/// A JSON string representation of the object.
///
[DebuggerStepThrough]
public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
{
return SerializeObject(value, null, formatting, settings);
}
///
/// Serializes the specified object to a JSON string using a type, formatting and .
///
/// The object to serialize.
/// Indicates how the output should be formatted.
/// The used to serialize the object.
/// If this is null, default serialization settings will be used.
///
/// The type of the value being serialized.
/// This parameter is used when is to write out the type name if the type of the value does not match.
/// Specifying the type is optional.
///
///
/// A JSON string representation of the object.
///
[DebuggerStepThrough]
public static string SerializeObject(object value, Type type, Formatting formatting, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
jsonSerializer.Formatting = formatting;
return SerializeObjectInternal(value, type, jsonSerializer);
}
private static string SerializeObjectInternal(object value, Type type, JsonSerializer jsonSerializer)
{
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = jsonSerializer.Formatting;
jsonSerializer.Serialize(jsonWriter, value, type);
}
return sw.ToString();
}
#endregion
#region Deserialize
///
/// Deserializes the JSON to a .NET object.
///
/// The JSON to deserialize.
/// The deserialized object from the JSON string.
[DebuggerStepThrough]
public static object DeserializeObject(string value)
{
return DeserializeObject(value, null, (JsonSerializerSettings)null);
}
///
/// Deserializes the JSON to a .NET object using .
///
/// The JSON to deserialize.
///
/// The used to deserialize the object.
/// If this is null, default serialization settings will be used.
///
/// The deserialized object from the JSON string.
[DebuggerStepThrough]
public static object DeserializeObject(string value, JsonSerializerSettings settings)
{
return DeserializeObject(value, null, settings);
}
///
/// Deserializes the JSON to the specified .NET type.
///
/// The JSON to deserialize.
/// The of object being deserialized.
/// The deserialized object from the JSON string.
[DebuggerStepThrough]
public static object DeserializeObject(string value, Type type)
{
return DeserializeObject(value, type, (JsonSerializerSettings)null);
}
///
/// Deserializes the JSON to the specified .NET type.
///
/// The type of the object to deserialize to.
/// The JSON to deserialize.
/// The deserialized object from the JSON string.
[DebuggerStepThrough]
public static T DeserializeObject(string value)
{
return DeserializeObject(value, (JsonSerializerSettings)null);
}
///
/// Deserializes the JSON to the given anonymous type.
///
///
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be inferred from the anonymous type passed
/// as a parameter.
///
/// The JSON to deserialize.
/// The anonymous type object.
/// The deserialized anonymous type from the JSON string.
[DebuggerStepThrough]
public static T DeserializeAnonymousType(string value, T anonymousTypeObject)
{
return DeserializeObject(value);
}
///
/// Deserializes the JSON to the given anonymous type using .
///
///
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be inferred from the anonymous type passed
/// as a parameter.
///
/// The JSON to deserialize.
/// The anonymous type object.
///
/// The used to deserialize the object.
/// If this is null, default serialization settings will be used.
///
/// The deserialized anonymous type from the JSON string.
[DebuggerStepThrough]
public static T DeserializeAnonymousType(string value, T anonymousTypeObject, JsonSerializerSettings settings)
{
return DeserializeObject(value, settings);
}
///
/// Deserializes the JSON to the specified .NET type using a collection of .
///
/// The type of the object to deserialize to.
/// The JSON to deserialize.
/// Converters to use while deserializing.
/// The deserialized object from the JSON string.
[DebuggerStepThrough]
public static T DeserializeObject(string value, params JsonConverter[] converters)
{
return (T)DeserializeObject(value, typeof(T), converters);
}
///
/// Deserializes the JSON to the specified .NET type using .
///
/// The type of the object to deserialize to.
/// The object to deserialize.
///
/// The used to deserialize the object.
/// If this is null, default serialization settings will be used.
///
/// The deserialized object from the JSON string.
[DebuggerStepThrough]
public static T DeserializeObject(string value, JsonSerializerSettings settings)
{
return (T)DeserializeObject(value, typeof(T), settings);
}
///
/// Deserializes the JSON to the specified .NET type using a collection of .
///
/// The JSON to deserialize.
/// The type of the object to deserialize.
/// Converters to use while deserializing.
/// The deserialized object from the JSON string.
[DebuggerStepThrough]
public static object DeserializeObject(string value, Type type, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return DeserializeObject(value, type, settings);
}
///
/// Deserializes the JSON to the specified .NET type using .
///
/// The JSON to deserialize.
/// The type of the object to deserialize to.
///
/// The used to deserialize the object.
/// If this is null, default serialization settings will be used.
///
/// The deserialized object from the JSON string.
public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
// by default DeserializeObject should check for additional content
if (!jsonSerializer.IsCheckAdditionalContentSet())
{
jsonSerializer.CheckAdditionalContent = true;
}
using (JsonTextReader reader = new JsonTextReader(new StringReader(value)))
{
return jsonSerializer.Deserialize(reader, type);
}
}
#endregion
#region Populate
///
/// Populates the object with values from the JSON string.
///
/// The JSON to populate values from.
/// The target object to populate values onto.
[DebuggerStepThrough]
public static void PopulateObject(string value, object target)
{
PopulateObject(value, target, null);
}
///
/// Populates the object with values from the JSON string using .
///
/// The JSON to populate values from.
/// The target object to populate values onto.
///
/// The used to deserialize the object.
/// If this is null, default serialization settings will be used.
///
public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
using (JsonReader jsonReader = new JsonTextReader(new StringReader(value)))
{
jsonSerializer.Populate(jsonReader, target);
if (settings != null && settings.CheckAdditionalContent)
{
while (jsonReader.Read())
{
if (jsonReader.TokenType != JsonToken.Comment)
{
throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object.");
}
}
}
}
}
#endregion
#region Xml
#if HAVE_XML_DOCUMENT
///
/// Serializes the to a JSON string.
///
/// The node to serialize.
/// A JSON string of the .
public static string SerializeXmlNode(XmlNode node)
{
return SerializeXmlNode(node, Formatting.None);
}
///
/// Serializes the to a JSON string using formatting.
///
/// The node to serialize.
/// Indicates how the output should be formatted.
/// A JSON string of the .
public static string SerializeXmlNode(XmlNode node, Formatting formatting)
{
XmlNodeConverter converter = new XmlNodeConverter();
return SerializeObject(node, formatting, converter);
}
///
/// Serializes the to a JSON string using formatting and omits the root object if is true.
///
/// The node to serialize.
/// Indicates how the output should be formatted.
/// Omits writing the root object.
/// A JSON string of the .
public static string SerializeXmlNode(XmlNode node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
return SerializeObject(node, formatting, converter);
}
///
/// Deserializes the from a JSON string.
///
/// The JSON string.
/// The deserialized .
public static XmlDocument DeserializeXmlNode(string value)
{
return DeserializeXmlNode(value, null);
}
///
/// Deserializes the from a JSON string nested in a root element specified by .
///
/// The JSON string.
/// The name of the root element to append when deserializing.
/// The deserialized .
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName)
{
return DeserializeXmlNode(value, deserializeRootElementName, false);
}
///
/// Deserializes the from a JSON string nested in a root element specified by
/// and writes a Json.NET array attribute for collections.
///
/// The JSON string.
/// The name of the root element to append when deserializing.
///
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
///
/// The deserialized .
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, false);
}
///
/// Deserializes the from a JSON string nested in a root element specified by ,
/// writes a Json.NET array attribute for collections, and encodes special characters.
///
/// The JSON string.
/// The name of the root element to append when deserializing.
///
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
///
///
/// A value to indicate whether to encode special characters when converting JSON to XML.
/// If true, special characters like ':', '@', '?', '#' and '$' in JSON property names aren't used to specify
/// XML namespaces, attributes or processing directives. Instead special characters are encoded and written
/// as part of the XML element name.
///
/// The deserialized .
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
converter.EncodeSpecialCharacters = encodeSpecialCharacters;
return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), converter);
}
#endif
#if HAVE_XLINQ
///
/// Serializes the to a JSON string.
///
/// The node to convert to JSON.
/// A JSON string of the .
public static string SerializeXNode(XObject node)
{
return SerializeXNode(node, Formatting.None);
}
///
/// Serializes the to a JSON string using formatting.
///
/// The node to convert to JSON.
/// Indicates how the output should be formatted.
/// A JSON string of the .
public static string SerializeXNode(XObject node, Formatting formatting)
{
return SerializeXNode(node, formatting, false);
}
///
/// Serializes the to a JSON string using formatting and omits the root object if is true.
///
/// The node to serialize.
/// Indicates how the output should be formatted.
/// Omits writing the root object.
/// A JSON string of the .
public static string SerializeXNode(XObject node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
return SerializeObject(node, formatting, converter);
}
///
/// Deserializes the from a JSON string.
///
/// The JSON string.
/// The deserialized .
public static XDocument DeserializeXNode(string value)
{
return DeserializeXNode(value, null);
}
///
/// Deserializes the from a JSON string nested in a root element specified by .
///
/// The JSON string.
/// The name of the root element to append when deserializing.
/// The deserialized .
public static XDocument DeserializeXNode(string value, string deserializeRootElementName)
{
return DeserializeXNode(value, deserializeRootElementName, false);
}
///
/// Deserializes the from a JSON string nested in a root element specified by
/// and writes a Json.NET array attribute for collections.
///
/// The JSON string.
/// The name of the root element to append when deserializing.
///
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
///
/// The deserialized .
public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, false);
}
///
/// Deserializes the from a JSON string nested in a root element specified by ,
/// writes a Json.NET array attribute for collections, and encodes special characters.
///
/// The JSON string.
/// The name of the root element to append when deserializing.
///
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
///
///
/// A value to indicate whether to encode special characters when converting JSON to XML.
/// If true, special characters like ':', '@', '?', '#' and '$' in JSON property names aren't used to specify
/// XML namespaces, attributes or processing directives. Instead special characters are encoded and written
/// as part of the XML element name.
///
/// The deserialized .
public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
converter.EncodeSpecialCharacters = encodeSpecialCharacters;
return (XDocument)DeserializeObject(value, typeof(XDocument), converter);
}
#endif
#endregion
}
}