/// <summary> /// Creates a JSON representation of a value using the converter specified in /// the type's attributes. /// </summary> /// <param name="instance">an instance of some type</param> /// <returns>the serialized JSON data as a string</returns> /// <exception cref="ArgumentException">if the type does not have a /// <c>[JsonStreamConverter]</c> attribute</exception> /// <seealso cref="JsonStreamConverterAttribute"/> /// <seealso cref="SerializeObjectToUtf8Bytes(object)"/> public static string SerializeObject(object instance) { if (instance is null) { return("null"); } return(SerializeObject(instance, JsonStreamConverterAttribute.ForTargetType(instance.GetType()).Converter)); }
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { var attr = JsonStreamConverterAttribute.ForTargetType(typeToConvert); return((JsonConverter)Activator.CreateInstance( typeof(ConverterImpl <>).MakeGenericType(typeToConvert), attr.Converter )); }
/// <summary> /// Same as <see cref="SerializeObject(object)"/>, but returns the JSON output /// as a byte array using UTF8 encoding. /// </summary> /// <param name="instance">an instance of some type</param> /// <returns>the serialized JSON data as a byte array</returns> /// <exception cref="ArgumentException">if the type does not have a /// <c>[JsonStreamConverter]</c> attribute</exception> /// <seealso cref="JsonStreamConverterAttribute"/> /// <seealso cref="SerializeObject(object)"/> public static byte[] SerializeObjectToUtf8Bytes(object instance) { var writer = JWriter.New(); if (instance is null) { writer.Null(); } else { SerializeObjectToJWriter(instance, writer, JsonStreamConverterAttribute.ForTargetType(instance.GetType()).Converter); } return(writer.GetUtf8Bytes()); }
/// <summary> /// Decodes a value from a JSON representation using the converter specified /// in the type's attributes. /// </summary> /// <remarks> /// This is the same as <see cref="DeserializeObject{T}(string)"/>, but for cases /// where the type is not known at compile time. /// </remarks> /// <param name="json">the JSON representation as a string</param> /// <param name="type">the desired type</param> /// <returns>an instance of that type</returns> /// <exception cref="ArgumentException">if the type does not have a /// <c>[JsonStreamConverter]</c> attribute</exception> /// <exception cref="JsonReadException">if an error occurred in parsing /// the JSON or translating it to the desired type; see subclasses of /// <see cref="JsonReadException"/> for more specific errors</exception> public static object DeserializeObject(string json, Type type) => DeserializeObject(json, JsonStreamConverterAttribute.ForTargetType(type).Converter);