Annotate for trim/AOT (in)compatibility (#2980)

Co-authored-by: James Newton-King <james@newtonking.com>
This commit is contained in:
Sven Boemer
2024-10-11 16:33:15 +08:00
committed by GitHub
co-authored by James Newton-King
parent 4738a64817
commit 9317d71ac5
76 changed files with 1233 additions and 60 deletions
@@ -29,6 +29,7 @@ using System.Globalization;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
#if HAVE_ADO_NET #if HAVE_ADO_NET
using System.Data.SqlTypes; using System.Data.SqlTypes;
#endif #endif
@@ -38,6 +39,8 @@ namespace Newtonsoft.Json.Converters
/// <summary> /// <summary>
/// Converts a binary value to and from a base 64 string value. /// Converts a binary value to and from a base 64 string value.
/// </summary> /// </summary>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class BinaryConverter : JsonConverter public class BinaryConverter : JsonConverter
{ {
#if HAVE_LINQ #if HAVE_LINQ
@@ -24,6 +24,7 @@
#endregion #endregion
using System; using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection; using System.Reflection;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
@@ -33,6 +34,8 @@ namespace Newtonsoft.Json.Converters
/// Creates a custom object. /// Creates a custom object.
/// </summary> /// </summary>
/// <typeparam name="T">The object type to convert.</typeparam> /// <typeparam name="T">The object type to convert.</typeparam>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public abstract class CustomCreationConverter<T> : JsonConverter public abstract class CustomCreationConverter<T> : JsonConverter
{ {
/// <summary> /// <summary>
@@ -26,13 +26,17 @@
#if HAVE_ADO_NET #if HAVE_ADO_NET
using System; using System;
using System.Data; using System.Data;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters namespace Newtonsoft.Json.Converters
{ {
/// <summary> /// <summary>
/// Converts a <see cref="DataSet"/> to and from JSON. /// Converts a <see cref="DataSet"/> to and from JSON.
/// </summary> /// </summary>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class DataSetConverter : JsonConverter public class DataSetConverter : JsonConverter
{ {
/// <summary> /// <summary>
@@ -26,6 +26,7 @@
#if HAVE_ADO_NET #if HAVE_ADO_NET
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
using System; using System;
@@ -37,6 +38,8 @@ namespace Newtonsoft.Json.Converters
/// <summary> /// <summary>
/// Converts a <see cref="DataTable"/> to and from JSON. /// Converts a <see cref="DataTable"/> to and from JSON.
/// </summary> /// </summary>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class DataTableConverter : JsonConverter public class DataTableConverter : JsonConverter
{ {
/// <summary> /// <summary>
@@ -28,6 +28,7 @@ using Newtonsoft.Json.Linq;
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#if !HAVE_LINQ #if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge; using Newtonsoft.Json.Utilities.LinqBridge;
#else #else
@@ -43,6 +44,8 @@ namespace Newtonsoft.Json.Converters
/// <summary> /// <summary>
/// Converts a F# discriminated union type to and from JSON. /// Converts a F# discriminated union type to and from JSON.
/// </summary> /// </summary>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class DiscriminatedUnionConverter : JsonConverter public class DiscriminatedUnionConverter : JsonConverter
{ {
#region UnionDefinition #region UnionDefinition
@@ -26,6 +26,7 @@
#if HAVE_ENTITY_FRAMEWORK #if HAVE_ENTITY_FRAMEWORK
using System; using System;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
using System.Diagnostics; using System.Diagnostics;
@@ -35,6 +36,8 @@ namespace Newtonsoft.Json.Converters
/// <summary> /// <summary>
/// Converts an Entity Framework <see cref="T:System.Data.EntityKeyMember"/> to and from JSON. /// Converts an Entity Framework <see cref="T:System.Data.EntityKeyMember"/> to and from JSON.
/// </summary> /// </summary>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class EntityKeyMemberConverter : JsonConverter public class EntityKeyMemberConverter : JsonConverter
{ {
private const string EntityKeyMemberFullTypeName = "System.Data.EntityKeyMember"; private const string EntityKeyMemberFullTypeName = "System.Data.EntityKeyMember";
@@ -157,7 +160,7 @@ namespace Newtonsoft.Json.Converters
/// </returns> /// </returns>
public override bool CanConvert(Type objectType) public override bool CanConvert(Type objectType)
{ {
return objectType.AssignableToTypeName(EntityKeyMemberFullTypeName, false); return objectType.AssignableToTypeName(EntityKeyMemberFullTypeName);
} }
} }
} }
@@ -25,6 +25,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
using System.Reflection; using System.Reflection;
@@ -34,6 +35,8 @@ namespace Newtonsoft.Json.Converters
/// <summary> /// <summary>
/// Converts a <see cref="KeyValuePair{TKey,TValue}"/> to and from JSON. /// Converts a <see cref="KeyValuePair{TKey,TValue}"/> to and from JSON.
/// </summary> /// </summary>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class KeyValuePairConverter : JsonConverter public class KeyValuePairConverter : JsonConverter
{ {
private const string KeyName = "Key"; private const string KeyName = "Key";
@@ -24,6 +24,7 @@
#endregion #endregion
using System; using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Newtonsoft.Json.Bson; using Newtonsoft.Json.Bson;
using System.Globalization; using System.Globalization;
@@ -36,6 +37,8 @@ namespace Newtonsoft.Json.Converters
/// <summary> /// <summary>
/// Converts a <see cref="Regex"/> to and from JSON and BSON. /// Converts a <see cref="Regex"/> to and from JSON and BSON.
/// </summary> /// </summary>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class RegexConverter : JsonConverter public class RegexConverter : JsonConverter
{ {
private const string PatternName = "Pattern"; private const string PatternName = "Pattern";
@@ -27,6 +27,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using System.Reflection; using System.Reflection;
using System.Runtime.Serialization; using System.Runtime.Serialization;
@@ -44,6 +45,8 @@ namespace Newtonsoft.Json.Converters
/// <summary> /// <summary>
/// Converts an <see cref="Enum"/> to and from its name string value. /// Converts an <see cref="Enum"/> to and from its name string value.
/// </summary> /// </summary>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class StringEnumConverter : JsonConverter public class StringEnumConverter : JsonConverter
{ {
/// <summary> /// <summary>
@@ -2198,13 +2198,13 @@ namespace Newtonsoft.Json.Converters
public override bool CanConvert(Type valueType) public override bool CanConvert(Type valueType)
{ {
#if HAVE_XLINQ #if HAVE_XLINQ
if (valueType.AssignableToTypeName("System.Xml.Linq.XObject", false)) if (valueType.AssignableToTypeName("System.Xml.Linq.XObject"))
{ {
return IsXObject(valueType); return IsXObject(valueType);
} }
#endif #endif
#if HAVE_XML_DOCUMENT #if HAVE_XML_DOCUMENT
if (valueType.AssignableToTypeName("System.Xml.XmlNode", false)) if (valueType.AssignableToTypeName("System.Xml.XmlNode"))
{ {
return IsXmlNode(valueType); return IsXmlNode(valueType);
} }
+70
View File
@@ -525,6 +525,8 @@ namespace Newtonsoft.Json
/// <param name="value">The object to serialize.</param> /// <param name="value">The object to serialize.</param>
/// <returns>A JSON string representation of the object.</returns> /// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static string SerializeObject(object? value) public static string SerializeObject(object? value)
{ {
return SerializeObject(value, null, (JsonSerializerSettings?)null); return SerializeObject(value, null, (JsonSerializerSettings?)null);
@@ -539,6 +541,8 @@ namespace Newtonsoft.Json
/// A JSON string representation of the object. /// A JSON string representation of the object.
/// </returns> /// </returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static string SerializeObject(object? value, Formatting formatting) public static string SerializeObject(object? value, Formatting formatting)
{ {
return SerializeObject(value, formatting, (JsonSerializerSettings?)null); return SerializeObject(value, formatting, (JsonSerializerSettings?)null);
@@ -551,6 +555,8 @@ namespace Newtonsoft.Json
/// <param name="converters">A collection of converters used while serializing.</param> /// <param name="converters">A collection of converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns> /// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static string SerializeObject(object? value, params JsonConverter[] converters) public static string SerializeObject(object? value, params JsonConverter[] converters)
{ {
JsonSerializerSettings? settings = (converters != null && converters.Length > 0) JsonSerializerSettings? settings = (converters != null && converters.Length > 0)
@@ -568,6 +574,8 @@ namespace Newtonsoft.Json
/// <param name="converters">A collection of converters used while serializing.</param> /// <param name="converters">A collection of converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns> /// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters) public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters)
{ {
JsonSerializerSettings? settings = (converters != null && converters.Length > 0) JsonSerializerSettings? settings = (converters != null && converters.Length > 0)
@@ -587,6 +595,8 @@ namespace Newtonsoft.Json
/// A JSON string representation of the object. /// A JSON string representation of the object.
/// </returns> /// </returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static string SerializeObject(object? value, JsonSerializerSettings? settings) public static string SerializeObject(object? value, JsonSerializerSettings? settings)
{ {
return SerializeObject(value, null, settings); return SerializeObject(value, null, settings);
@@ -607,6 +617,8 @@ namespace Newtonsoft.Json
/// A JSON string representation of the object. /// A JSON string representation of the object.
/// </returns> /// </returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings) public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings)
{ {
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
@@ -625,6 +637,8 @@ namespace Newtonsoft.Json
/// A JSON string representation of the object. /// A JSON string representation of the object.
/// </returns> /// </returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings) public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings)
{ {
return SerializeObject(value, null, formatting, settings); return SerializeObject(value, null, formatting, settings);
@@ -646,6 +660,8 @@ namespace Newtonsoft.Json
/// A JSON string representation of the object. /// A JSON string representation of the object.
/// </returns> /// </returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings) public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings)
{ {
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
@@ -654,6 +670,8 @@ namespace Newtonsoft.Json
return SerializeObjectInternal(value, type, jsonSerializer); return SerializeObjectInternal(value, type, jsonSerializer);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer) private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer)
{ {
StringBuilder sb = new StringBuilder(256); StringBuilder sb = new StringBuilder(256);
@@ -676,6 +694,8 @@ namespace Newtonsoft.Json
/// <param name="value">The JSON to deserialize.</param> /// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the JSON string.</returns> /// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static object? DeserializeObject(string value) public static object? DeserializeObject(string value)
{ {
return DeserializeObject(value, null, (JsonSerializerSettings?)null); return DeserializeObject(value, null, (JsonSerializerSettings?)null);
@@ -691,6 +711,8 @@ namespace Newtonsoft.Json
/// </param> /// </param>
/// <returns>The deserialized object from the JSON string.</returns> /// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static object? DeserializeObject(string value, JsonSerializerSettings settings) public static object? DeserializeObject(string value, JsonSerializerSettings settings)
{ {
return DeserializeObject(value, null, settings); return DeserializeObject(value, null, settings);
@@ -703,6 +725,8 @@ namespace Newtonsoft.Json
/// <param name="type">The <see cref="Type"/> of object being deserialized.</param> /// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The deserialized object from the JSON string.</returns> /// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static object? DeserializeObject(string value, Type type) public static object? DeserializeObject(string value, Type type)
{ {
return DeserializeObject(value, type, (JsonSerializerSettings?)null); return DeserializeObject(value, type, (JsonSerializerSettings?)null);
@@ -715,6 +739,8 @@ namespace Newtonsoft.Json
/// <param name="value">The JSON to deserialize.</param> /// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the JSON string.</returns> /// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static T? DeserializeObject<T>(string value) public static T? DeserializeObject<T>(string value)
{ {
return DeserializeObject<T>(value, (JsonSerializerSettings?)null); return DeserializeObject<T>(value, (JsonSerializerSettings?)null);
@@ -732,6 +758,8 @@ namespace Newtonsoft.Json
/// <param name="anonymousTypeObject">The anonymous type object.</param> /// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <returns>The deserialized anonymous type from the JSON string.</returns> /// <returns>The deserialized anonymous type from the JSON string.</returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject) public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
{ {
return DeserializeObject<T>(value); return DeserializeObject<T>(value);
@@ -753,6 +781,8 @@ namespace Newtonsoft.Json
/// </param> /// </param>
/// <returns>The deserialized anonymous type from the JSON string.</returns> /// <returns>The deserialized anonymous type from the JSON string.</returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings) public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings)
{ {
return DeserializeObject<T>(value, settings); return DeserializeObject<T>(value, settings);
@@ -766,6 +796,8 @@ namespace Newtonsoft.Json
/// <param name="converters">Converters to use while deserializing.</param> /// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns> /// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static T? DeserializeObject<T>(string value, params JsonConverter[] converters) public static T? DeserializeObject<T>(string value, params JsonConverter[] converters)
{ {
return (T?)DeserializeObject(value, typeof(T), converters); return (T?)DeserializeObject(value, typeof(T), converters);
@@ -782,6 +814,8 @@ namespace Newtonsoft.Json
/// </param> /// </param>
/// <returns>The deserialized object from the JSON string.</returns> /// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings) public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings)
{ {
return (T?)DeserializeObject(value, typeof(T), settings); return (T?)DeserializeObject(value, typeof(T), settings);
@@ -795,6 +829,8 @@ namespace Newtonsoft.Json
/// <param name="converters">Converters to use while deserializing.</param> /// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns> /// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters) public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters)
{ {
JsonSerializerSettings? settings = (converters != null && converters.Length > 0) JsonSerializerSettings? settings = (converters != null && converters.Length > 0)
@@ -814,6 +850,8 @@ namespace Newtonsoft.Json
/// If this is <c>null</c>, default serialization settings will be used. /// If this is <c>null</c>, default serialization settings will be used.
/// </param> /// </param>
/// <returns>The deserialized object from the JSON string.</returns> /// <returns>The deserialized object from the JSON string.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings) public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings)
{ {
ValidationUtils.ArgumentNotNull(value, nameof(value)); ValidationUtils.ArgumentNotNull(value, nameof(value));
@@ -840,6 +878,8 @@ namespace Newtonsoft.Json
/// <param name="value">The JSON to populate values from.</param> /// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param> /// <param name="target">The target object to populate values onto.</param>
[DebuggerStepThrough] [DebuggerStepThrough]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static void PopulateObject(string value, object target) public static void PopulateObject(string value, object target)
{ {
PopulateObject(value, target, null); PopulateObject(value, target, null);
@@ -854,6 +894,8 @@ namespace Newtonsoft.Json
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object. /// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used. /// If this is <c>null</c>, default serialization settings will be used.
/// </param> /// </param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static void PopulateObject(string value, object target, JsonSerializerSettings? settings) public static void PopulateObject(string value, object target, JsonSerializerSettings? settings)
{ {
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
@@ -883,6 +925,8 @@ namespace Newtonsoft.Json
/// </summary> /// </summary>
/// <param name="node">The node to serialize.</param> /// <param name="node">The node to serialize.</param>
/// <returns>A JSON string of the <see cref="XmlNode"/>.</returns> /// <returns>A JSON string of the <see cref="XmlNode"/>.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static string SerializeXmlNode(XmlNode? node) public static string SerializeXmlNode(XmlNode? node)
{ {
return SerializeXmlNode(node, Formatting.None); return SerializeXmlNode(node, Formatting.None);
@@ -894,6 +938,8 @@ namespace Newtonsoft.Json
/// <param name="node">The node to serialize.</param> /// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param> /// <param name="formatting">Indicates how the output should be formatted.</param>
/// <returns>A JSON string of the <see cref="XmlNode"/>.</returns> /// <returns>A JSON string of the <see cref="XmlNode"/>.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static string SerializeXmlNode(XmlNode? node, Formatting formatting) public static string SerializeXmlNode(XmlNode? node, Formatting formatting)
{ {
XmlNodeConverter converter = new XmlNodeConverter(); XmlNodeConverter converter = new XmlNodeConverter();
@@ -908,6 +954,8 @@ namespace Newtonsoft.Json
/// <param name="formatting">Indicates how the output should be formatted.</param> /// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param> /// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the <see cref="XmlNode"/>.</returns> /// <returns>A JSON string of the <see cref="XmlNode"/>.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject) public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject)
{ {
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject }; XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
@@ -920,6 +968,8 @@ namespace Newtonsoft.Json
/// </summary> /// </summary>
/// <param name="value">The JSON string.</param> /// <param name="value">The JSON string.</param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns> /// <returns>The deserialized <see cref="XmlNode"/>.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static XmlDocument? DeserializeXmlNode(string value) public static XmlDocument? DeserializeXmlNode(string value)
{ {
return DeserializeXmlNode(value, null); return DeserializeXmlNode(value, null);
@@ -931,6 +981,8 @@ namespace Newtonsoft.Json
/// <param name="value">The JSON string.</param> /// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param> /// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns> /// <returns>The deserialized <see cref="XmlNode"/>.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName) public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName)
{ {
return DeserializeXmlNode(value, deserializeRootElementName, false); return DeserializeXmlNode(value, deserializeRootElementName, false);
@@ -947,6 +999,8 @@ namespace Newtonsoft.Json
/// This attribute helps preserve arrays when converting the written XML back to JSON. /// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param> /// </param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns> /// <returns>The deserialized <see cref="XmlNode"/>.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
{ {
return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, false); return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, false);
@@ -969,6 +1023,8 @@ namespace Newtonsoft.Json
/// as part of the XML element name. /// as part of the XML element name.
/// </param> /// </param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns> /// <returns>The deserialized <see cref="XmlNode"/>.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
{ {
XmlNodeConverter converter = new XmlNodeConverter(); XmlNodeConverter converter = new XmlNodeConverter();
@@ -986,6 +1042,8 @@ namespace Newtonsoft.Json
/// </summary> /// </summary>
/// <param name="node">The node to convert to JSON.</param> /// <param name="node">The node to convert to JSON.</param>
/// <returns>A JSON string of the <see cref="XNode"/>.</returns> /// <returns>A JSON string of the <see cref="XNode"/>.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static string SerializeXNode(XObject? node) public static string SerializeXNode(XObject? node)
{ {
return SerializeXNode(node, Formatting.None); return SerializeXNode(node, Formatting.None);
@@ -997,6 +1055,8 @@ namespace Newtonsoft.Json
/// <param name="node">The node to convert to JSON.</param> /// <param name="node">The node to convert to JSON.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param> /// <param name="formatting">Indicates how the output should be formatted.</param>
/// <returns>A JSON string of the <see cref="XNode"/>.</returns> /// <returns>A JSON string of the <see cref="XNode"/>.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static string SerializeXNode(XObject? node, Formatting formatting) public static string SerializeXNode(XObject? node, Formatting formatting)
{ {
return SerializeXNode(node, formatting, false); return SerializeXNode(node, formatting, false);
@@ -1009,6 +1069,8 @@ namespace Newtonsoft.Json
/// <param name="formatting">Indicates how the output should be formatted.</param> /// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param> /// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the <see cref="XNode"/>.</returns> /// <returns>A JSON string of the <see cref="XNode"/>.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject) public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject)
{ {
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject }; XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
@@ -1021,6 +1083,8 @@ namespace Newtonsoft.Json
/// </summary> /// </summary>
/// <param name="value">The JSON string.</param> /// <param name="value">The JSON string.</param>
/// <returns>The deserialized <see cref="XNode"/>.</returns> /// <returns>The deserialized <see cref="XNode"/>.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static XDocument? DeserializeXNode(string value) public static XDocument? DeserializeXNode(string value)
{ {
return DeserializeXNode(value, null); return DeserializeXNode(value, null);
@@ -1032,6 +1096,8 @@ namespace Newtonsoft.Json
/// <param name="value">The JSON string.</param> /// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param> /// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized <see cref="XNode"/>.</returns> /// <returns>The deserialized <see cref="XNode"/>.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName) public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName)
{ {
return DeserializeXNode(value, deserializeRootElementName, false); return DeserializeXNode(value, deserializeRootElementName, false);
@@ -1048,6 +1114,8 @@ namespace Newtonsoft.Json
/// This attribute helps preserve arrays when converting the written XML back to JSON. /// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param> /// </param>
/// <returns>The deserialized <see cref="XNode"/>.</returns> /// <returns>The deserialized <see cref="XNode"/>.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
{ {
return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, false); return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, false);
@@ -1070,6 +1138,8 @@ namespace Newtonsoft.Json
/// as part of the XML element name. /// as part of the XML element name.
/// </param> /// </param>
/// <returns>The deserialized <see cref="XNode"/>.</returns> /// <returns>The deserialized <see cref="XNode"/>.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
{ {
XmlNodeConverter converter = new XmlNodeConverter(); XmlNodeConverter converter = new XmlNodeConverter();
+2
View File
@@ -44,6 +44,8 @@ namespace Newtonsoft.Json
/// Serializes and deserializes objects into and from the JSON format. /// Serializes and deserializes objects into and from the JSON format.
/// The <see cref="JsonSerializer"/> enables you to control how objects are encoded into JSON. /// The <see cref="JsonSerializer"/> enables you to control how objects are encoded into JSON.
/// </summary> /// </summary>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class JsonSerializer public class JsonSerializer
{ {
internal TypeNameHandling _typeNameHandling; internal TypeNameHandling _typeNameHandling;
+3
View File
@@ -25,6 +25,7 @@
#if HAVE_ASYNC #if HAVE_ASYNC
using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -41,6 +42,8 @@ namespace Newtonsoft.Json.Linq
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns> /// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override async Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) public override async Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters)
{ {
await writer.WriteStartArrayAsync(cancellationToken).ConfigureAwait(false); await writer.WriteStartArrayAsync(cancellationToken).ConfigureAwait(false);
+7
View File
@@ -26,6 +26,7 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
using System.IO; using System.IO;
using System.Globalization; using System.Globalization;
@@ -188,6 +189,8 @@ namespace Newtonsoft.Json.Linq
/// </summary> /// </summary>
/// <param name="o">The object that will be used to create <see cref="JArray"/>.</param> /// <param name="o">The object that will be used to create <see cref="JArray"/>.</param>
/// <returns>A <see cref="JArray"/> with the values of the specified object.</returns> /// <returns>A <see cref="JArray"/> with the values of the specified object.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public new static JArray FromObject(object o) public new static JArray FromObject(object o)
{ {
return FromObject(o, JsonSerializer.CreateDefault()); return FromObject(o, JsonSerializer.CreateDefault());
@@ -199,6 +202,8 @@ namespace Newtonsoft.Json.Linq
/// <param name="o">The object that will be used to create <see cref="JArray"/>.</param> /// <param name="o">The object that will be used to create <see cref="JArray"/>.</param>
/// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used to read the object.</param> /// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used to read the object.</param>
/// <returns>A <see cref="JArray"/> with the values of the specified object.</returns> /// <returns>A <see cref="JArray"/> with the values of the specified object.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public new static JArray FromObject(object o, JsonSerializer jsonSerializer) public new static JArray FromObject(object o, JsonSerializer jsonSerializer)
{ {
JToken token = FromObjectInternal(o, jsonSerializer); JToken token = FromObjectInternal(o, jsonSerializer);
@@ -216,6 +221,8 @@ namespace Newtonsoft.Json.Linq
/// </summary> /// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
{ {
writer.WriteStartArray(); writer.WriteStartArray();
@@ -25,6 +25,7 @@
#if HAVE_ASYNC #if HAVE_ASYNC
using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -41,6 +42,8 @@ namespace Newtonsoft.Json.Linq
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns> /// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override async Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) public override async Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters)
{ {
await writer.WriteStartConstructorAsync(_name ?? string.Empty, cancellationToken).ConfigureAwait(false); await writer.WriteStartConstructorAsync(_name ?? string.Empty, cancellationToken).ConfigureAwait(false);
+3
View File
@@ -26,6 +26,7 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
using System.Globalization; using System.Globalization;
@@ -163,6 +164,8 @@ namespace Newtonsoft.Json.Linq
/// </summary> /// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
{ {
writer.WriteStartConstructor(_name!); writer.WriteStartConstructor(_name!);
+8
View File
@@ -959,9 +959,17 @@ namespace Newtonsoft.Json.Linq
PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors)
{ {
#if HAVE_APPCONTEXT
if (!ComponentModelIsSupported)
{
throw new NotSupportedException(ComponentModelNotSupportedMessage);
}
#endif
ICustomTypeDescriptor? d = First as ICustomTypeDescriptor; ICustomTypeDescriptor? d = First as ICustomTypeDescriptor;
#pragma warning disable IL2026
return d?.GetProperties() ?? new PropertyDescriptorCollection(CollectionUtils.ArrayEmpty<PropertyDescriptor>()); return d?.GetProperties() ?? new PropertyDescriptorCollection(CollectionUtils.ArrayEmpty<PropertyDescriptor>());
#pragma warning restore IL2026
} }
#endif #endif
@@ -26,6 +26,7 @@
#if HAVE_ASYNC #if HAVE_ASYNC
using System; using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -42,6 +43,8 @@ namespace Newtonsoft.Json.Linq
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns> /// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters)
{ {
Task t = writer.WriteStartObjectAsync(cancellationToken); Task t = writer.WriteStartObjectAsync(cancellationToken);
@@ -62,6 +65,7 @@ namespace Newtonsoft.Json.Linq
return writer.WriteEndObjectAsync(cancellationToken); return writer.WriteEndObjectAsync(cancellationToken);
// Local functions, params renamed (capitalized) so as not to capture and allocate when calling async // Local functions, params renamed (capitalized) so as not to capture and allocate when calling async
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
async Task AwaitProperties(Task task, int i, JsonWriter Writer, CancellationToken CancellationToken, JsonConverter[] Converters) async Task AwaitProperties(Task task, int i, JsonWriter Writer, CancellationToken CancellationToken, JsonConverter[] Converters)
{ {
await task.ConfigureAwait(false); await task.ConfigureAwait(false);
+21
View File
@@ -485,6 +485,8 @@ namespace Newtonsoft.Json.Linq
/// </summary> /// </summary>
/// <param name="o">The object that will be used to create <see cref="JObject"/>.</param> /// <param name="o">The object that will be used to create <see cref="JObject"/>.</param>
/// <returns>A <see cref="JObject"/> with the values of the specified object.</returns> /// <returns>A <see cref="JObject"/> with the values of the specified object.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public new static JObject FromObject(object o) public new static JObject FromObject(object o)
{ {
return FromObject(o, JsonSerializer.CreateDefault()); return FromObject(o, JsonSerializer.CreateDefault());
@@ -496,6 +498,8 @@ namespace Newtonsoft.Json.Linq
/// <param name="o">The object that will be used to create <see cref="JObject"/>.</param> /// <param name="o">The object that will be used to create <see cref="JObject"/>.</param>
/// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used to read the object.</param> /// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used to read the object.</param>
/// <returns>A <see cref="JObject"/> with the values of the specified object.</returns> /// <returns>A <see cref="JObject"/> with the values of the specified object.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public new static JObject FromObject(object o, JsonSerializer jsonSerializer) public new static JObject FromObject(object o, JsonSerializer jsonSerializer)
{ {
JToken token = FromObjectInternal(o, jsonSerializer); JToken token = FromObjectInternal(o, jsonSerializer);
@@ -513,6 +517,8 @@ namespace Newtonsoft.Json.Linq
/// </summary> /// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
{ {
writer.WriteStartObject(); writer.WriteStartObject();
@@ -742,11 +748,13 @@ namespace Newtonsoft.Json.Linq
// include custom type descriptor on JObject rather than use a provider because the properties are specific to a type // include custom type descriptor on JObject rather than use a provider because the properties are specific to a type
#region ICustomTypeDescriptor #region ICustomTypeDescriptor
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{ {
return ((ICustomTypeDescriptor)this).GetProperties(null); return ((ICustomTypeDescriptor)this).GetProperties(null);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[]? attributes) PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[]? attributes)
{ {
PropertyDescriptor[] propertiesArray = new PropertyDescriptor[Count]; PropertyDescriptor[] propertiesArray = new PropertyDescriptor[Count];
@@ -775,26 +783,31 @@ namespace Newtonsoft.Json.Linq
return null; return null;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
TypeConverter ICustomTypeDescriptor.GetConverter() TypeConverter ICustomTypeDescriptor.GetConverter()
{ {
return new TypeConverter(); return new TypeConverter();
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
EventDescriptor? ICustomTypeDescriptor.GetDefaultEvent() EventDescriptor? ICustomTypeDescriptor.GetDefaultEvent()
{ {
return null; return null;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
PropertyDescriptor? ICustomTypeDescriptor.GetDefaultProperty() PropertyDescriptor? ICustomTypeDescriptor.GetDefaultProperty()
{ {
return null; return null;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
object? ICustomTypeDescriptor.GetEditor(Type editorBaseType) object? ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{ {
return null; return null;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[]? attributes) EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[]? attributes)
{ {
return EventDescriptorCollection.Empty; return EventDescriptorCollection.Empty;
@@ -828,7 +841,15 @@ namespace Newtonsoft.Json.Linq
/// </returns> /// </returns>
protected override DynamicMetaObject GetMetaObject(Expression parameter) protected override DynamicMetaObject GetMetaObject(Expression parameter)
{ {
#if HAVE_APPCONTEXT
if (!DynamicIsSupported)
{
throw new NotSupportedException(DynamicNotSupportedMessage);
}
#endif
#pragma warning disable IL2026, IL3050
return new DynamicProxyMetaObject<JObject>(parameter, this, new JObjectDynamicProxy()); return new DynamicProxyMetaObject<JObject>(parameter, this, new JObjectDynamicProxy());
#pragma warning restore IL2026, IL3050
} }
private class JObjectDynamicProxy : DynamicProxy<JObject> private class JObjectDynamicProxy : DynamicProxy<JObject>
@@ -25,6 +25,7 @@
#if HAVE_ASYNC #if HAVE_ASYNC
using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -41,6 +42,8 @@ namespace Newtonsoft.Json.Linq
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns> /// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters)
{ {
Task task = writer.WritePropertyNameAsync(_name, cancellationToken); Task task = writer.WritePropertyNameAsync(_name, cancellationToken);
@@ -52,6 +55,8 @@ namespace Newtonsoft.Json.Linq
return WriteToAsync(task, writer, cancellationToken, converters); return WriteToAsync(task, writer, cancellationToken, converters);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private async Task WriteToAsync(Task task, JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) private async Task WriteToAsync(Task task, JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters)
{ {
await task.ConfigureAwait(false); await task.ConfigureAwait(false);
@@ -59,6 +64,8 @@ namespace Newtonsoft.Json.Linq
await WriteValueAsync(writer, cancellationToken, converters).ConfigureAwait(false); await WriteValueAsync(writer, cancellationToken, converters).ConfigureAwait(false);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private Task WriteValueAsync(JsonWriter writer, CancellationToken cancellationToken, JsonConverter[] converters) private Task WriteValueAsync(JsonWriter writer, CancellationToken cancellationToken, JsonConverter[] converters)
{ {
JToken value = Value; JToken value = Value;
+3
View File
@@ -26,6 +26,7 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
using System.Diagnostics; using System.Diagnostics;
using System.Globalization; using System.Globalization;
@@ -342,6 +343,8 @@ namespace Newtonsoft.Json.Linq
/// </summary> /// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
{ {
writer.WritePropertyName(_name); writer.WritePropertyName(_name);
+30
View File
@@ -26,6 +26,7 @@
#if HAVE_ASYNC #if HAVE_ASYNC
using System; using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -42,6 +43,8 @@ namespace Newtonsoft.Json.Linq
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns> /// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public virtual Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) public virtual Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
@@ -53,11 +56,38 @@ namespace Newtonsoft.Json.Linq
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns> /// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public Task WriteToAsync(JsonWriter writer, params JsonConverter[] converters) public Task WriteToAsync(JsonWriter writer, params JsonConverter[] converters)
{ {
return WriteToAsync(writer, default, converters); return WriteToAsync(writer, default, converters);
} }
/// <summary>
/// Writes this token to a <see cref="JsonWriter"/> asynchronously.
/// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns>
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "WriteToAsync without converters is safe.")]
[UnconditionalSuppressMessage("AOT", "IL3050", Justification = "WriteToAsync without converters is safe.")]
public Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken)
{
return WriteToAsync(writer, default, CollectionUtils.ArrayEmpty<JsonConverter>());
}
/// <summary>
/// Writes this token to a <see cref="JsonWriter"/> asynchronously.
/// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns>
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "WriteToAsync without converters is safe.")]
[UnconditionalSuppressMessage("AOT", "IL3050", Justification = "WriteToAsync without converters is safe.")]
public Task WriteToAsync(JsonWriter writer)
{
return WriteToAsync(writer, default, CollectionUtils.ArrayEmpty<JsonConverter>());
}
/// <summary> /// <summary>
/// Asynchronously creates a <see cref="JToken"/> from a <see cref="JsonReader"/>. /// Asynchronously creates a <see cref="JToken"/> from a <see cref="JsonReader"/>.
/// </summary> /// </summary>
+82
View File
@@ -80,6 +80,33 @@ namespace Newtonsoft.Json.Linq
private static readonly JTokenType[] DateTimeTypes = new[] { JTokenType.Date, JTokenType.String, JTokenType.Comment, JTokenType.Raw }; private static readonly JTokenType[] DateTimeTypes = new[] { JTokenType.Date, JTokenType.String, JTokenType.Comment, JTokenType.Raw };
private static readonly JTokenType[] BytesTypes = new[] { JTokenType.Bytes, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Integer }; private static readonly JTokenType[] BytesTypes = new[] { JTokenType.Bytes, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Integer };
#if HAVE_APPCONTEXT
[FeatureSwitchDefinition("Newtonsoft.Json.Linq.JToken.SerializationIsSupported")]
[FeatureGuard(typeof(RequiresUnreferencedCodeAttribute))]
[FeatureGuard(typeof(RequiresDynamicCodeAttribute))]
internal static bool SerializationIsSupported => AppContext.TryGetSwitch("Newtonsoft.Json.Linq.JToken.SerializationIsSupported", out bool isSupported) ? isSupported : true;
internal const string SerializationNotSupportedMessage = "Newtonsoft.Json serialization is not compatible with trimming and has been disabled. Newtonsoft.Json.Linq.JToken.SerializationIsSupported is set to false.";
#if HAVE_COMPONENT_MODEL
[FeatureSwitchDefinition("Newtonsoft.Json.Linq.JToken.ComponentModelIsSupported")]
[FeatureGuard(typeof(RequiresUnreferencedCodeAttribute))]
internal static bool ComponentModelIsSupported => AppContext.TryGetSwitch("Newtonsoft.Json.Linq.JToken.ComponentModelIsSupported", out bool isSupported) ? isSupported : true;
internal const string ComponentModelNotSupportedMessage = "Newtonsoft.Json support for System.ComponentModel is not compatible with trimming and has been disabled. Newtonsoft.Json.Linq.JToken.ComponentModelIsSupported is set to false.";
#endif // HAVE_COMPONENT_MODEL
#if HAVE_DYNAMIC
[FeatureSwitchDefinition("Newtonsoft.Json.Linq.JToken.DynamicIsSupported")]
[FeatureGuard(typeof(RequiresUnreferencedCodeAttribute))]
[FeatureGuard(typeof(RequiresDynamicCodeAttribute))]
internal static bool DynamicIsSupported => AppContext.TryGetSwitch("Newtonsoft.Json.Linq.JToken.DynamicIsSupported", out bool isSupported) ? isSupported : true;
internal const string DynamicNotSupportedMessage = "Newtonsoft.Json support for dynamic is not compatible with trimming and has been disabled. Newtonsoft.Json.Linq.JToken.DynamicIsSupported is set to false.";
#endif // HAVE_DYNAMIC
#endif // HAVE_APPCONTEXT
/// <summary> /// <summary>
/// Gets a comparer that can compare two tokens for value equality. /// Gets a comparer that can compare two tokens for value equality.
/// </summary> /// </summary>
@@ -411,11 +438,24 @@ namespace Newtonsoft.Json.Linq
_parent.ReplaceItem(this, value); _parent.ReplaceItem(this, value);
} }
/// <summary>
/// Writes this token to a <see cref="JsonWriter"/>.
/// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "WriteTo without converters is safe.")]
[UnconditionalSuppressMessage("AOT", "IL3050", Justification = "WriteTo without converters is safe.")]
public void WriteTo(JsonWriter writer)
{
WriteTo(writer, CollectionUtils.ArrayEmpty<JsonConverter>());
}
/// <summary> /// <summary>
/// Writes this token to a <see cref="JsonWriter"/>. /// Writes this token to a <see cref="JsonWriter"/>.
/// </summary> /// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public abstract void WriteTo(JsonWriter writer, params JsonConverter[] converters); public abstract void WriteTo(JsonWriter writer, params JsonConverter[] converters);
/// <summary> /// <summary>
@@ -433,12 +473,32 @@ namespace Newtonsoft.Json.Linq
return ToString(Formatting.Indented); return ToString(Formatting.Indented);
} }
/// <summary>
/// Returns the JSON for this token using the given formatting and converters.
/// </summary>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <returns>The JSON for this token using the given formatting and converters.</returns>
public string ToString(Formatting formatting)
{
using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
{
JsonTextWriter jw = new JsonTextWriter(sw);
jw.Formatting = formatting;
WriteTo(jw);
return sw.ToString();
}
}
/// <summary> /// <summary>
/// Returns the JSON for this token using the given formatting and converters. /// Returns the JSON for this token using the given formatting and converters.
/// </summary> /// </summary>
/// <param name="formatting">Indicates how the output should be formatted.</param> /// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/>s which will be used when writing the token.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/>s which will be used when writing the token.</param>
/// <returns>The JSON for this token using the given formatting and converters.</returns> /// <returns>The JSON for this token using the given formatting and converters.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public string ToString(Formatting formatting, params JsonConverter[] converters) public string ToString(Formatting formatting, params JsonConverter[] converters)
{ {
using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)) using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
@@ -1889,6 +1949,8 @@ namespace Newtonsoft.Json.Linq
return new JTokenReader(this); return new JTokenReader(this);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
internal static JToken FromObjectInternal(object o, JsonSerializer jsonSerializer) internal static JToken FromObjectInternal(object o, JsonSerializer jsonSerializer)
{ {
ValidationUtils.ArgumentNotNull(o, nameof(o)); ValidationUtils.ArgumentNotNull(o, nameof(o));
@@ -1909,6 +1971,8 @@ namespace Newtonsoft.Json.Linq
/// </summary> /// </summary>
/// <param name="o">The object that will be used to create <see cref="JToken"/>.</param> /// <param name="o">The object that will be used to create <see cref="JToken"/>.</param>
/// <returns>A <see cref="JToken"/> with the value of the specified object.</returns> /// <returns>A <see cref="JToken"/> with the value of the specified object.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static JToken FromObject(object o) public static JToken FromObject(object o)
{ {
return FromObjectInternal(o, JsonSerializer.CreateDefault()); return FromObjectInternal(o, JsonSerializer.CreateDefault());
@@ -1920,6 +1984,8 @@ namespace Newtonsoft.Json.Linq
/// <param name="o">The object that will be used to create <see cref="JToken"/>.</param> /// <param name="o">The object that will be used to create <see cref="JToken"/>.</param>
/// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used when reading the object.</param> /// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used when reading the object.</param>
/// <returns>A <see cref="JToken"/> with the value of the specified object.</returns> /// <returns>A <see cref="JToken"/> with the value of the specified object.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static JToken FromObject(object o, JsonSerializer jsonSerializer) public static JToken FromObject(object o, JsonSerializer jsonSerializer)
{ {
return FromObjectInternal(o, jsonSerializer); return FromObjectInternal(o, jsonSerializer);
@@ -1930,6 +1996,8 @@ namespace Newtonsoft.Json.Linq
/// </summary> /// </summary>
/// <typeparam name="T">The object type that the token will be deserialized to.</typeparam> /// <typeparam name="T">The object type that the token will be deserialized to.</typeparam>
/// <returns>The new object created from the JSON value.</returns> /// <returns>The new object created from the JSON value.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public T? ToObject<T>() public T? ToObject<T>()
{ {
return (T?)ToObject(typeof(T)); return (T?)ToObject(typeof(T));
@@ -1940,6 +2008,8 @@ namespace Newtonsoft.Json.Linq
/// </summary> /// </summary>
/// <param name="objectType">The object type that the token will be deserialized to.</param> /// <param name="objectType">The object type that the token will be deserialized to.</param>
/// <returns>The new object created from the JSON value.</returns> /// <returns>The new object created from the JSON value.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public object? ToObject(Type objectType) public object? ToObject(Type objectType)
{ {
if (JsonConvert.DefaultSettings == null) if (JsonConvert.DefaultSettings == null)
@@ -2063,6 +2133,8 @@ namespace Newtonsoft.Json.Linq
/// <typeparam name="T">The object type that the token will be deserialized to.</typeparam> /// <typeparam name="T">The object type that the token will be deserialized to.</typeparam>
/// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used when creating the object.</param> /// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used when creating the object.</param>
/// <returns>The new object created from the JSON value.</returns> /// <returns>The new object created from the JSON value.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public T? ToObject<T>(JsonSerializer jsonSerializer) public T? ToObject<T>(JsonSerializer jsonSerializer)
{ {
return (T?)ToObject(typeof(T), jsonSerializer); return (T?)ToObject(typeof(T), jsonSerializer);
@@ -2074,6 +2146,8 @@ namespace Newtonsoft.Json.Linq
/// <param name="objectType">The object type that the token will be deserialized to.</param> /// <param name="objectType">The object type that the token will be deserialized to.</param>
/// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used when creating the object.</param> /// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used when creating the object.</param>
/// <returns>The new object created from the JSON value.</returns> /// <returns>The new object created from the JSON value.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public object? ToObject(Type? objectType, JsonSerializer jsonSerializer) public object? ToObject(Type? objectType, JsonSerializer jsonSerializer)
{ {
ValidationUtils.ArgumentNotNull(jsonSerializer, nameof(jsonSerializer)); ValidationUtils.ArgumentNotNull(jsonSerializer, nameof(jsonSerializer));
@@ -2414,7 +2488,15 @@ namespace Newtonsoft.Json.Linq
/// </returns> /// </returns>
protected virtual DynamicMetaObject GetMetaObject(Expression parameter) protected virtual DynamicMetaObject GetMetaObject(Expression parameter)
{ {
#if HAVE_APPCONTEXT
if (!DynamicIsSupported)
{
throw new NotSupportedException(DynamicNotSupportedMessage);
}
#endif
#pragma warning disable IL2026, IL3050
return new DynamicProxyMetaObject<JToken>(parameter, this, new DynamicProxy<JToken>()); return new DynamicProxyMetaObject<JToken>(parameter, this, new DynamicProxy<JToken>());
#pragma warning restore IL2026, IL3050
} }
/// <summary> /// <summary>
+3
View File
@@ -26,6 +26,7 @@
#if HAVE_ASYNC #if HAVE_ASYNC
using System; using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
#if HAVE_BIG_INTEGER #if HAVE_BIG_INTEGER
using System.Numerics; using System.Numerics;
@@ -45,6 +46,8 @@ namespace Newtonsoft.Json.Linq
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns> /// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters)
{ {
if (converters != null && converters.Length > 0 && _value != null) if (converters != null && converters.Length > 0 && _value != null)
+20
View File
@@ -727,6 +727,8 @@ namespace Newtonsoft.Json.Linq
/// </summary> /// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/>s which will be used when writing the token.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/>s which will be used when writing the token.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
{ {
if (converters != null && converters.Length > 0 && _value != null) if (converters != null && converters.Length > 0 && _value != null)
@@ -972,9 +974,19 @@ namespace Newtonsoft.Json.Linq
/// </returns> /// </returns>
protected override DynamicMetaObject GetMetaObject(Expression parameter) protected override DynamicMetaObject GetMetaObject(Expression parameter)
{ {
#if HAVE_APPCONTEXT
if (!DynamicIsSupported)
{
throw new NotSupportedException(DynamicNotSupportedMessage);
}
#endif
#pragma warning disable IL2026, IL3050
return new DynamicProxyMetaObject<JValue>(parameter, this, new JValueDynamicProxy()); return new DynamicProxyMetaObject<JValue>(parameter, this, new JValueDynamicProxy());
#pragma warning restore IL2026, IL3050
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private class JValueDynamicProxy : DynamicProxy<JValue> private class JValueDynamicProxy : DynamicProxy<JValue>
{ {
public override bool TryConvert(JValue instance, ConvertBinder binder, [NotNullWhen(true)]out object? result) public override bool TryConvert(JValue instance, ConvertBinder binder, [NotNullWhen(true)]out object? result)
@@ -1188,7 +1200,15 @@ namespace Newtonsoft.Json.Linq
object IConvertible.ToType(Type conversionType, IFormatProvider? provider) object IConvertible.ToType(Type conversionType, IFormatProvider? provider)
{ {
#if HAVE_APPCONTEXT
if (!SerializationIsSupported)
{
throw new NotSupportedException(SerializationNotSupportedMessage);
}
#endif
#pragma warning disable IL2026, IL3050
return ToObject(conversionType)!; return ToObject(conversionType)!;
#pragma warning restore IL2026, IL3050
} }
#endif #endif
} }
+14 -4
View File
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFrameworks Condition="'$(LibraryFrameworks)'==''">net6.0;net45;net40;net35;net20;netstandard1.0;netstandard1.3;netstandard2.0</TargetFrameworks> <TargetFrameworks Condition="'$(LibraryFrameworks)'==''">net8.0;net6.0;net45;net40;net35;net20;netstandard1.0;netstandard1.3;netstandard2.0</TargetFrameworks>
<TargetFrameworks Condition="'$(LibraryFrameworks)'!=''">$(LibraryFrameworks)</TargetFrameworks> <TargetFrameworks Condition="'$(LibraryFrameworks)'!=''">$(LibraryFrameworks)</TargetFrameworks>
<LangVersion>9.0</LangVersion> <LangVersion>9.0</LangVersion>
<!-- version numbers will be updated by build --> <!-- version numbers will be updated by build -->
@@ -40,6 +40,12 @@
Disable that warning since local builds do not strong-name sign the assembly, causing a mistmatch when comparing Disable that warning since local builds do not strong-name sign the assembly, causing a mistmatch when comparing
the previously shipped assemblies and current.--> the previously shipped assemblies and current.-->
<NoWarn Condition="'$(SignAssembly)' != 'true'">$(NoWarn);CP0003</NoWarn> <NoWarn Condition="'$(SignAssembly)' != 'true'">$(NoWarn);CP0003</NoWarn>
<!-- Enable the trim/aot/single-file analyzers for all TargetFrameworks where they are supported. -->
<!-- We enable the analyzers directly instead of setting IsTrimmable or IsAotCompatible, to avoid adding IsTrimmable assembly metadata.
This should help avoid breaking consumers who use partial TrimMode. -->
<EnableSingleFileAnalyzer Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net6.0'))">true</EnableSingleFileAnalyzer>
<EnableTrimAnalyzer Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net6.0'))">true</EnableTrimAnalyzer>
<EnableAotAnalyzer Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net7.0'))">true</EnableAotAnalyzer>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<None Remove="**\*.orig" /> <None Remove="**\*.orig" />
@@ -51,9 +57,13 @@
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="$(MicrosoftCodeAnalysisNetAnalyzersPackageVersion)" PrivateAssets="All" /> <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="$(MicrosoftCodeAnalysisNetAnalyzersPackageVersion)" PrivateAssets="All" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="$(MicrosoftSourceLinkGitHubPackageVersion)" PrivateAssets="All" /> <PackageReference Include="Microsoft.SourceLink.GitHub" Version="$(MicrosoftSourceLinkGitHubPackageVersion)" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net8.0'">
<AssemblyTitle>Json.NET .NET 8.0</AssemblyTitle>
<DefineConstants>HAVE_APPCONTEXT;HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_ASYNC_DISPOSABLE;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_INDEXOF_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_GETHASHCODE_STRING_COMPARISON;HAVE_NULLABLE_ATTRIBUTES;HAVE_DYNAMIC_CODE_COMPILED;HAS_ARRAY_EMPTY;HAVE_DATE_ONLY;$(AdditionalConstants)</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net6.0'"> <PropertyGroup Condition="'$(TargetFramework)'=='net6.0'">
<AssemblyTitle>Json.NET .NET 6.0</AssemblyTitle> <AssemblyTitle>Json.NET .NET 6.0</AssemblyTitle>
<DefineConstants>HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_ASYNC_DISPOSABLE;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_INDEXOF_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_GETHASHCODE_STRING_COMPARISON;HAVE_NULLABLE_ATTRIBUTES;HAVE_DYNAMIC_CODE_COMPILED;HAS_ARRAY_EMPTY;HAVE_DATE_ONLY;$(AdditionalConstants)</DefineConstants> <DefineConstants>HAVE_APPCONTEXT;HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_ASYNC_DISPOSABLE;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_INDEXOF_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_GETHASHCODE_STRING_COMPARISON;HAVE_NULLABLE_ATTRIBUTES;HAVE_DYNAMIC_CODE_COMPILED;HAS_ARRAY_EMPTY;HAVE_DATE_ONLY;$(AdditionalConstants)</DefineConstants>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net45'"> <PropertyGroup Condition="'$(TargetFramework)'=='net45'">
<AssemblyTitle>Json.NET .NET 4.5</AssemblyTitle> <AssemblyTitle>Json.NET .NET 4.5</AssemblyTitle>
@@ -86,10 +96,10 @@
</ItemGroup> </ItemGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'netstandard1.3'"> <PropertyGroup Condition="'$(TargetFramework)' == 'netstandard1.3'">
<AssemblyTitle>Json.NET .NET Standard 1.3</AssemblyTitle> <AssemblyTitle>Json.NET .NET Standard 1.3</AssemblyTitle>
<DefineConstants>NETSTANDARD1_3;PORTABLE;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_SERIALIZATION;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DYNAMIC;HAVE_EXPRESSIONS;HAVE_FSHARP_TYPES;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_BINDER;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;HAVE_XML_DOCUMENT;HAVE_CONCURRENT_DICTIONARY;HAVE_ICONVERTIBLE;HAVE_REGEX_TIMEOUTS;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants)</DefineConstants> <DefineConstants>HAVE_APPCONTEXT;NETSTANDARD1_3;PORTABLE;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_SERIALIZATION;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DYNAMIC;HAVE_EXPRESSIONS;HAVE_FSHARP_TYPES;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_BINDER;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;HAVE_XML_DOCUMENT;HAVE_CONCURRENT_DICTIONARY;HAVE_ICONVERTIBLE;HAVE_REGEX_TIMEOUTS;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants)</DefineConstants>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'netstandard2.0'"> <PropertyGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<AssemblyTitle>Json.NET .NET Standard 2.0</AssemblyTitle> <AssemblyTitle>Json.NET .NET Standard 2.0</AssemblyTitle>
<DefineConstants>NETSTANDARD2_0;HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants)</DefineConstants> <DefineConstants>HAVE_APPCONTEXT;NETSTANDARD2_0;HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants)</DefineConstants>
</PropertyGroup> </PropertyGroup>
</Project> </Project>
+9
View File
@@ -25,6 +25,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
@@ -57,6 +58,8 @@ namespace Newtonsoft.Json.Schema
/// <c>true</c> if the specified <see cref="JToken"/> is valid; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="JToken"/> is valid; otherwise, <c>false</c>.
/// </returns> /// </returns>
[Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static bool IsValid(this JToken source, JsonSchema schema) public static bool IsValid(this JToken source, JsonSchema schema)
{ {
bool valid = true; bool valid = true;
@@ -79,6 +82,8 @@ namespace Newtonsoft.Json.Schema
/// <c>true</c> if the specified <see cref="JToken"/> is valid; otherwise, <c>false</c>. /// <c>true</c> if the specified <see cref="JToken"/> is valid; otherwise, <c>false</c>.
/// </returns> /// </returns>
[Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static bool IsValid(this JToken source, JsonSchema schema, out IList<string> errorMessages) public static bool IsValid(this JToken source, JsonSchema schema, out IList<string> errorMessages)
{ {
IList<string> errors = new List<string>(); IList<string> errors = new List<string>();
@@ -100,6 +105,8 @@ namespace Newtonsoft.Json.Schema
/// <param name="source">The source <see cref="JToken"/> to test.</param> /// <param name="source">The source <see cref="JToken"/> to test.</param>
/// <param name="schema">The schema to test with.</param> /// <param name="schema">The schema to test with.</param>
[Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static void Validate(this JToken source, JsonSchema schema) public static void Validate(this JToken source, JsonSchema schema)
{ {
source.Validate(schema, null); source.Validate(schema, null);
@@ -117,6 +124,8 @@ namespace Newtonsoft.Json.Schema
/// <param name="schema">The schema to test with.</param> /// <param name="schema">The schema to test with.</param>
/// <param name="validationEventHandler">The validation event handler.</param> /// <param name="validationEventHandler">The validation event handler.</param>
[Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")]
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static void Validate(this JToken source, JsonSchema schema, ValidationEventHandler validationEventHandler) public static void Validate(this JToken source, JsonSchema schema, ValidationEventHandler validationEventHandler)
{ {
ValidationUtils.ArgumentNotNull(source, nameof(source)); ValidationUtils.ArgumentNotNull(source, nameof(source));
+13
View File
@@ -25,6 +25,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO; using System.IO;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
@@ -318,6 +319,8 @@ namespace Newtonsoft.Json.Schema
/// Writes this schema to a <see cref="JsonWriter"/>. /// Writes this schema to a <see cref="JsonWriter"/>.
/// </summary> /// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public void WriteTo(JsonWriter writer) public void WriteTo(JsonWriter writer)
{ {
WriteTo(writer, new JsonSchemaResolver()); WriteTo(writer, new JsonSchemaResolver());
@@ -328,6 +331,8 @@ namespace Newtonsoft.Json.Schema
/// </summary> /// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="resolver">The resolver used.</param> /// <param name="resolver">The resolver used.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public void WriteTo(JsonWriter writer, JsonSchemaResolver resolver) public void WriteTo(JsonWriter writer, JsonSchemaResolver resolver)
{ {
ValidationUtils.ArgumentNotNull(writer, nameof(writer)); ValidationUtils.ArgumentNotNull(writer, nameof(writer));
@@ -345,11 +350,19 @@ namespace Newtonsoft.Json.Schema
/// </returns> /// </returns>
public override string ToString() public override string ToString()
{ {
#if HAVE_APPCONTEXT
if (!JToken.SerializationIsSupported)
{
throw new NotSupportedException(JToken.SerializationNotSupportedMessage);
}
#endif
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture); StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
JsonTextWriter jsonWriter = new JsonTextWriter(writer); JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented; jsonWriter.Formatting = Formatting.Indented;
#pragma warning disable IL2026, IL3050
WriteTo(jsonWriter); WriteTo(jsonWriter);
#pragma warning restore IL2026, IL3050
return writer.ToString(); return writer.ToString();
} }
@@ -30,6 +30,8 @@ using System.Collections.Generic;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using System.Diagnostics.CodeAnalysis;
#if !HAVE_LINQ #if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge; using Newtonsoft.Json.Utilities.LinqBridge;
#else #else
@@ -65,6 +67,8 @@ namespace Newtonsoft.Json.Schema
/// <value>The contract resolver.</value> /// <value>The contract resolver.</value>
public IContractResolver ContractResolver public IContractResolver ContractResolver
{ {
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
get get
{ {
if (_contractResolver == null) if (_contractResolver == null)
@@ -127,6 +131,8 @@ namespace Newtonsoft.Json.Schema
/// </summary> /// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public JsonSchema Generate(Type type) public JsonSchema Generate(Type type)
{ {
return Generate(type, new JsonSchemaResolver(), false); return Generate(type, new JsonSchemaResolver(), false);
@@ -138,6 +144,8 @@ namespace Newtonsoft.Json.Schema
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param> /// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public JsonSchema Generate(Type type, JsonSchemaResolver resolver) public JsonSchema Generate(Type type, JsonSchemaResolver resolver)
{ {
return Generate(type, resolver, false); return Generate(type, resolver, false);
@@ -149,6 +157,8 @@ namespace Newtonsoft.Json.Schema
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param> /// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public JsonSchema Generate(Type type, bool rootSchemaNullable) public JsonSchema Generate(Type type, bool rootSchemaNullable)
{ {
return Generate(type, new JsonSchemaResolver(), rootSchemaNullable); return Generate(type, new JsonSchemaResolver(), rootSchemaNullable);
@@ -161,6 +171,8 @@ namespace Newtonsoft.Json.Schema
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param> /// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param> /// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable) public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable)
{ {
ValidationUtils.ArgumentNotNull(type, nameof(type)); ValidationUtils.ArgumentNotNull(type, nameof(type));
@@ -171,6 +183,8 @@ namespace Newtonsoft.Json.Schema
return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false); return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private string GetTitle(Type type) private string GetTitle(Type type)
{ {
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type); JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type);
@@ -183,6 +197,8 @@ namespace Newtonsoft.Json.Schema
return null; return null;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private string GetDescription(Type type) private string GetDescription(Type type)
{ {
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type); JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type);
@@ -200,6 +216,8 @@ namespace Newtonsoft.Json.Schema
#endif #endif
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private string GetTypeId(Type type, bool explicitOnly) private string GetTypeId(Type type, bool explicitOnly)
{ {
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type); JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type);
@@ -225,7 +243,13 @@ namespace Newtonsoft.Json.Schema
} }
} }
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private JsonSchema GenerateInternal(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)]
Type type,
Required valueRequired,
bool required)
{ {
ValidationUtils.ArgumentNotNull(type, nameof(type)); ValidationUtils.ArgumentNotNull(type, nameof(type));
@@ -382,6 +406,8 @@ namespace Newtonsoft.Json.Schema
return ((value & flag) == flag); return ((value & flag) == flag);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void GenerateObjectSchema(Type type, JsonObjectContract contract) private void GenerateObjectSchema(Type type, JsonObjectContract contract)
{ {
CurrentSchema.Properties = new Dictionary<string, JsonSchema>(); CurrentSchema.Properties = new Dictionary<string, JsonSchema>();
@@ -25,6 +25,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
@@ -52,6 +53,8 @@ namespace Newtonsoft.Json.Schema
_resolver = resolver; _resolver = resolver;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void ReferenceOrWriteSchema(JsonSchema schema) private void ReferenceOrWriteSchema(JsonSchema schema)
{ {
if (schema.Id != null && _resolver.GetSchema(schema.Id) != null) if (schema.Id != null && _resolver.GetSchema(schema.Id) != null)
@@ -67,6 +70,8 @@ namespace Newtonsoft.Json.Schema
} }
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public void WriteSchema(JsonSchema schema) public void WriteSchema(JsonSchema schema)
{ {
ValidationUtils.ArgumentNotNull(schema, nameof(schema)); ValidationUtils.ArgumentNotNull(schema, nameof(schema));
@@ -167,6 +172,8 @@ namespace Newtonsoft.Json.Schema
_writer.WriteEndObject(); _writer.WriteEndObject();
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void WriteSchemaDictionaryIfNotNull(JsonWriter writer, string propertyName, IDictionary<string, JsonSchema> properties) private void WriteSchemaDictionaryIfNotNull(JsonWriter writer, string propertyName, IDictionary<string, JsonSchema> properties)
{ {
if (properties != null) if (properties != null)
@@ -182,6 +189,8 @@ namespace Newtonsoft.Json.Schema
} }
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void WriteItems(JsonSchema schema) private void WriteItems(JsonSchema schema)
{ {
if (schema.Items == null && !schema.PositionalItemsValidation) if (schema.Items == null && !schema.PositionalItemsValidation)
@@ -24,11 +24,14 @@
#endregion #endregion
using System; using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection; using System.Reflection;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization namespace Newtonsoft.Json.Serialization
{ {
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
internal static class CachedAttributeGetter<T> where T : Attribute internal static class CachedAttributeGetter<T> where T : Attribute
{ {
private static readonly ThreadSafeStore<object, T?> TypeAttributeCache = new ThreadSafeStore<object, T?>(JsonTypeReflector.GetAttribute<T>); private static readonly ThreadSafeStore<object, T?> TypeAttributeCache = new ThreadSafeStore<object, T?>(JsonTypeReflector.GetAttribute<T>);
@@ -25,6 +25,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
@@ -33,6 +34,8 @@ namespace Newtonsoft.Json.Serialization
/// <summary> /// <summary>
/// Resolves member mappings for a type, camel casing property names. /// Resolves member mappings for a type, camel casing property names.
/// </summary> /// </summary>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class CamelCasePropertyNamesContractResolver : DefaultContractResolver public class CamelCasePropertyNamesContractResolver : DefaultContractResolver
{ {
private static readonly object TypeContractCacheLock = new object(); private static readonly object TypeContractCacheLock = new object();
@@ -31,6 +31,7 @@ using System.Collections.Concurrent;
using Newtonsoft.Json.Schema; using Newtonsoft.Json.Schema;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
#if HAVE_DYNAMIC #if HAVE_DYNAMIC
using System.Dynamic; using System.Dynamic;
#endif #endif
@@ -58,6 +59,8 @@ namespace Newtonsoft.Json.Serialization
/// <summary> /// <summary>
/// Used by <see cref="JsonSerializer"/> to resolve a <see cref="JsonContract"/> for a given <see cref="System.Type"/>. /// Used by <see cref="JsonSerializer"/> to resolve a <see cref="JsonContract"/> for a given <see cref="System.Type"/>.
/// </summary> /// </summary>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class DefaultContractResolver : IContractResolver public class DefaultContractResolver : IContractResolver
{ {
private static readonly IContractResolver _instance = new DefaultContractResolver(); private static readonly IContractResolver _instance = new DefaultContractResolver();
@@ -290,7 +293,7 @@ namespace Newtonsoft.Json.Serialization
#if HAVE_DATA_CONTRACTS #if HAVE_DATA_CONTRACTS
// don't include EntityKey on entities objects... this is a bit hacky // don't include EntityKey on entities objects... this is a bit hacky
if (objectType.AssignableToTypeName("System.Data.Objects.DataClasses.EntityObject", false, out _)) if (objectType.AssignableToTypeName("System.Data.Objects.DataClasses.EntityObject", out _))
{ {
serializableMembers = serializableMembers.Where(ShouldSerializeEntityMember).ToList(); serializableMembers = serializableMembers.Where(ShouldSerializeEntityMember).ToList();
} }
@@ -24,6 +24,7 @@
#endregion #endregion
using System; using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using System.Reflection; using System.Reflection;
using System.Globalization; using System.Globalization;
@@ -35,6 +36,8 @@ namespace Newtonsoft.Json.Serialization
/// <summary> /// <summary>
/// The default serialization binder used when resolving and loading classes from type names. /// The default serialization binder used when resolving and loading classes from type names.
/// </summary> /// </summary>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class DefaultSerializationBinder : public class DefaultSerializationBinder :
#pragma warning disable 618 #pragma warning disable 618
SerializationBinder, SerializationBinder,
@@ -33,12 +33,14 @@ using System.Text;
using System.Reflection; using System.Reflection;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
using System.Globalization; using System.Globalization;
using System.Diagnostics.CodeAnalysis;
namespace Newtonsoft.Json.Serialization namespace Newtonsoft.Json.Serialization
{ {
/// <summary> /// <summary>
/// Get and set values for a <see cref="MemberInfo"/> using dynamic methods. /// Get and set values for a <see cref="MemberInfo"/> using dynamic methods.
/// </summary> /// </summary>
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class DynamicValueProvider : IValueProvider public class DynamicValueProvider : IValueProvider
{ {
private readonly MemberInfo _memberInfo; private readonly MemberInfo _memberInfo;
@@ -34,12 +34,14 @@ using System.Text;
using System.Reflection; using System.Reflection;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
using System.Globalization; using System.Globalization;
using System.Diagnostics.CodeAnalysis;
namespace Newtonsoft.Json.Serialization namespace Newtonsoft.Json.Serialization
{ {
/// <summary> /// <summary>
/// Get and set values for a <see cref="MemberInfo"/> using dynamic methods. /// Get and set values for a <see cref="MemberInfo"/> using dynamic methods.
/// </summary> /// </summary>
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class ExpressionValueProvider : IValueProvider public class ExpressionValueProvider : IValueProvider
{ {
private readonly MemberInfo _memberInfo; private readonly MemberInfo _memberInfo;
@@ -32,6 +32,8 @@ using System.Reflection;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
using System.Collections; using System.Collections;
using System.Diagnostics; using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
#if !HAVE_LINQ #if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge; using Newtonsoft.Json.Utilities.LinqBridge;
#else #else
@@ -60,6 +62,7 @@ namespace Newtonsoft.Json.Serialization
private readonly Type? _genericCollectionDefinitionType; private readonly Type? _genericCollectionDefinitionType;
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
private Type? _genericWrapperType; private Type? _genericWrapperType;
private ObjectConstructor<object>? _genericWrapperCreator; private ObjectConstructor<object>? _genericWrapperCreator;
private Func<object>? _genericTemporaryCollectionCreator; private Func<object>? _genericTemporaryCollectionCreator;
@@ -75,6 +78,7 @@ namespace Newtonsoft.Json.Serialization
internal ObjectConstructor<object>? ParameterizedCreator internal ObjectConstructor<object>? ParameterizedCreator
{ {
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
get get
{ {
if (_parameterizedCreator == null && _parameterizedConstructor != null) if (_parameterizedCreator == null && _parameterizedConstructor != null)
@@ -113,6 +117,8 @@ namespace Newtonsoft.Json.Serialization
/// Initializes a new instance of the <see cref="JsonArrayContract"/> class. /// Initializes a new instance of the <see cref="JsonArrayContract"/> class.
/// </summary> /// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param> /// <param name="underlyingType">The underlying type for the contract.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public JsonArrayContract(Type underlyingType) public JsonArrayContract(Type underlyingType)
: base(underlyingType) : base(underlyingType)
{ {
@@ -269,6 +275,7 @@ namespace Newtonsoft.Json.Serialization
} }
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
internal IWrappedCollection CreateWrapper(object list) internal IWrappedCollection CreateWrapper(object list)
{ {
if (_genericWrapperCreator == null) if (_genericWrapperCreator == null)
@@ -297,6 +304,7 @@ namespace Newtonsoft.Json.Serialization
return (IWrappedCollection)_genericWrapperCreator(list); return (IWrappedCollection)_genericWrapperCreator(list);
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
internal IList CreateTemporaryCollection() internal IList CreateTemporaryCollection()
{ {
if (_genericTemporaryCollectionCreator == null) if (_genericTemporaryCollectionCreator == null)
@@ -314,6 +322,8 @@ namespace Newtonsoft.Json.Serialization
} }
#if HAVE_FSHARP_TYPES #if HAVE_FSHARP_TYPES
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void StoreFSharpListCreatorIfNecessary(Type underlyingType) private void StoreFSharpListCreatorIfNecessary(Type underlyingType)
{ {
if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpListTypeName) if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpListTypeName)
@@ -25,6 +25,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection; using System.Reflection;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
using System.Collections; using System.Collections;
@@ -94,6 +95,8 @@ namespace Newtonsoft.Json.Serialization
/// Initializes a new instance of the <see cref="JsonContainerContract"/> class. /// Initializes a new instance of the <see cref="JsonContainerContract"/> class.
/// </summary> /// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param> /// <param name="underlyingType">The underlying type for the contract.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
internal JsonContainerContract(Type underlyingType) internal JsonContainerContract(Type underlyingType)
: base(underlyingType) : base(underlyingType)
{ {
@@ -26,6 +26,7 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection; using System.Reflection;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
@@ -83,6 +84,8 @@ namespace Newtonsoft.Json.Serialization
internal bool IsNullable; internal bool IsNullable;
internal bool IsConvertable; internal bool IsConvertable;
internal bool IsEnum; internal bool IsEnum;
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
internal Type NonNullableUnderlyingType; internal Type NonNullableUnderlyingType;
internal ReadType InternalReadType; internal ReadType InternalReadType;
internal JsonContractType ContractType; internal JsonContractType ContractType;
@@ -95,6 +98,8 @@ namespace Newtonsoft.Json.Serialization
private List<SerializationCallback>? _onSerializedCallbacks; private List<SerializationCallback>? _onSerializedCallbacks;
private List<SerializationCallback>? _onSerializingCallbacks; private List<SerializationCallback>? _onSerializingCallbacks;
private List<SerializationErrorCallback>? _onErrorCallbacks; private List<SerializationErrorCallback>? _onErrorCallbacks;
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
private Type _createdType; private Type _createdType;
/// <summary> /// <summary>
@@ -107,6 +112,7 @@ namespace Newtonsoft.Json.Serialization
/// Gets or sets the type created during deserialization. /// Gets or sets the type created during deserialization.
/// </summary> /// </summary>
/// <value>The type created during deserialization.</value> /// <value>The type created during deserialization.</value>
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
public Type CreatedType public Type CreatedType
{ {
get => _createdType; get => _createdType;
@@ -236,7 +242,10 @@ namespace Newtonsoft.Json.Serialization
/// <value><c>true</c> if the default object creator is non-public; otherwise, <c>false</c>.</value> /// <value><c>true</c> if the default object creator is non-public; otherwise, <c>false</c>.</value>
public bool DefaultCreatorNonPublic { get; set; } public bool DefaultCreatorNonPublic { get; set; }
internal JsonContract(Type underlyingType) [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
internal JsonContract(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
Type underlyingType)
{ {
ValidationUtils.ArgumentNotNull(underlyingType, nameof(underlyingType)); ValidationUtils.ArgumentNotNull(underlyingType, nameof(underlyingType));
@@ -29,6 +29,7 @@ using System.Collections.ObjectModel;
using System.Reflection; using System.Reflection;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
using System.Collections; using System.Collections;
using System.Diagnostics.CodeAnalysis;
#if !HAVE_LINQ #if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge; using Newtonsoft.Json.Utilities.LinqBridge;
@@ -63,6 +64,7 @@ namespace Newtonsoft.Json.Serialization
private readonly Type? _genericCollectionDefinitionType; private readonly Type? _genericCollectionDefinitionType;
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
private Type? _genericWrapperType; private Type? _genericWrapperType;
private ObjectConstructor<object>? _genericWrapperCreator; private ObjectConstructor<object>? _genericWrapperCreator;
@@ -77,6 +79,7 @@ namespace Newtonsoft.Json.Serialization
internal ObjectConstructor<object>? ParameterizedCreator internal ObjectConstructor<object>? ParameterizedCreator
{ {
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
get get
{ {
if (_parameterizedCreator == null && _parameterizedConstructor != null) if (_parameterizedCreator == null && _parameterizedConstructor != null)
@@ -110,6 +113,8 @@ namespace Newtonsoft.Json.Serialization
/// Initializes a new instance of the <see cref="JsonDictionaryContract"/> class. /// Initializes a new instance of the <see cref="JsonDictionaryContract"/> class.
/// </summary> /// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param> /// <param name="underlyingType">The underlying type for the contract.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public JsonDictionaryContract(Type underlyingType) public JsonDictionaryContract(Type underlyingType)
: base(underlyingType) : base(underlyingType)
{ {
@@ -219,6 +224,7 @@ namespace Newtonsoft.Json.Serialization
} }
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
internal IWrappedDictionary CreateWrapper(object dictionary) internal IWrappedDictionary CreateWrapper(object dictionary)
{ {
if (_genericWrapperCreator == null) if (_genericWrapperCreator == null)
@@ -232,6 +238,7 @@ namespace Newtonsoft.Json.Serialization
return (IWrappedDictionary)_genericWrapperCreator(dictionary); return (IWrappedDictionary)_genericWrapperCreator(dictionary);
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
internal IDictionary CreateTemporaryDictionary() internal IDictionary CreateTemporaryDictionary()
{ {
if (_genericTemporaryDictionaryCreator == null) if (_genericTemporaryDictionaryCreator == null)
@@ -25,6 +25,7 @@
#if HAVE_DYNAMIC #if HAVE_DYNAMIC
using System; using System;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic; using System.Dynamic;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
@@ -54,6 +55,8 @@ namespace Newtonsoft.Json.Serialization
private readonly ThreadSafeStore<string, CallSite<Func<CallSite, object, object?, object>>> _callSiteSetters = private readonly ThreadSafeStore<string, CallSite<Func<CallSite, object, object?, object>>> _callSiteSetters =
new ThreadSafeStore<string, CallSite<Func<CallSite, object, object?, object>>>(CreateCallSiteSetter); new ThreadSafeStore<string, CallSite<Func<CallSite, object, object?, object>>>(CreateCallSiteSetter);
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static CallSite<Func<CallSite, object, object>> CreateCallSiteGetter(string name) private static CallSite<Func<CallSite, object, object>> CreateCallSiteGetter(string name)
{ {
GetMemberBinder getMemberBinder = (GetMemberBinder)DynamicUtils.BinderWrapper.GetMember(name, typeof(DynamicUtils)); GetMemberBinder getMemberBinder = (GetMemberBinder)DynamicUtils.BinderWrapper.GetMember(name, typeof(DynamicUtils));
@@ -61,6 +64,8 @@ namespace Newtonsoft.Json.Serialization
return CallSite<Func<CallSite, object, object>>.Create(new NoThrowGetBinderMember(getMemberBinder)); return CallSite<Func<CallSite, object, object>>.Create(new NoThrowGetBinderMember(getMemberBinder));
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static CallSite<Func<CallSite, object, object?, object>> CreateCallSiteSetter(string name) private static CallSite<Func<CallSite, object, object?, object>> CreateCallSiteSetter(string name)
{ {
SetMemberBinder binder = (SetMemberBinder)DynamicUtils.BinderWrapper.SetMember(name, typeof(DynamicUtils)); SetMemberBinder binder = (SetMemberBinder)DynamicUtils.BinderWrapper.SetMember(name, typeof(DynamicUtils));
@@ -72,6 +77,8 @@ namespace Newtonsoft.Json.Serialization
/// Initializes a new instance of the <see cref="JsonDynamicContract"/> class. /// Initializes a new instance of the <see cref="JsonDynamicContract"/> class.
/// </summary> /// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param> /// <param name="underlyingType">The underlying type for the contract.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public JsonDynamicContract(Type underlyingType) public JsonDynamicContract(Type underlyingType)
: base(underlyingType) : base(underlyingType)
{ {
@@ -25,6 +25,7 @@
#if HAVE_BINARY_SERIALIZATION #if HAVE_BINARY_SERIALIZATION
using System; using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
@@ -32,6 +33,8 @@ using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Serialization namespace Newtonsoft.Json.Serialization
{ {
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
internal class JsonFormatterConverter : IFormatterConverter internal class JsonFormatterConverter : IFormatterConverter
{ {
private readonly JsonSerializerInternalReader _reader; private readonly JsonSerializerInternalReader _reader;
@@ -26,6 +26,8 @@
#if HAVE_BINARY_SERIALIZATION #if HAVE_BINARY_SERIALIZATION
using System; using System;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization namespace Newtonsoft.Json.Serialization
{ {
@@ -44,6 +46,8 @@ namespace Newtonsoft.Json.Serialization
/// Initializes a new instance of the <see cref="JsonISerializableContract"/> class. /// Initializes a new instance of the <see cref="JsonISerializableContract"/> class.
/// </summary> /// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param> /// <param name="underlyingType">The underlying type for the contract.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public JsonISerializableContract(Type underlyingType) public JsonISerializableContract(Type underlyingType)
: base(underlyingType) : base(underlyingType)
{ {
@@ -24,6 +24,8 @@
#endregion #endregion
using System; using System;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization namespace Newtonsoft.Json.Serialization
{ {
@@ -36,6 +38,7 @@ namespace Newtonsoft.Json.Serialization
/// Initializes a new instance of the <see cref="JsonLinqContract"/> class. /// Initializes a new instance of the <see cref="JsonLinqContract"/> class.
/// </summary> /// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param> /// <param name="underlyingType">The underlying type for the contract.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
public JsonLinqContract(Type underlyingType) public JsonLinqContract(Type underlyingType)
: base(underlyingType) : base(underlyingType)
{ {
@@ -24,6 +24,7 @@
#endregion #endregion
using System; using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using System.Reflection; using System.Reflection;
using System.Runtime.Serialization; using System.Runtime.Serialization;
@@ -172,6 +173,8 @@ namespace Newtonsoft.Json.Serialization
/// Initializes a new instance of the <see cref="JsonObjectContract"/> class. /// Initializes a new instance of the <see cref="JsonObjectContract"/> class.
/// </summary> /// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param> /// <param name="underlyingType">The underlying type for the contract.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public JsonObjectContract(Type underlyingType) public JsonObjectContract(Type underlyingType)
: base(underlyingType) : base(underlyingType)
{ {
@@ -25,6 +25,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization namespace Newtonsoft.Json.Serialization
@@ -40,6 +41,7 @@ namespace Newtonsoft.Json.Serialization
/// Initializes a new instance of the <see cref="JsonPrimitiveContract"/> class. /// Initializes a new instance of the <see cref="JsonPrimitiveContract"/> class.
/// </summary> /// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param> /// <param name="underlyingType">The underlying type for the contract.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
public JsonPrimitiveContract(Type underlyingType) public JsonPrimitiveContract(Type underlyingType)
: base(underlyingType) : base(underlyingType)
{ {
@@ -25,6 +25,7 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection; using System.Reflection;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
@@ -46,6 +47,8 @@ namespace Newtonsoft.Json.Serialization
private bool _hasGeneratedDefaultValue; private bool _hasGeneratedDefaultValue;
private string? _propertyName; private string? _propertyName;
internal bool _skipPropertyNameEscape; internal bool _skipPropertyNameEscape;
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
private Type? _propertyType; private Type? _propertyType;
// use to cache contract during deserialization // use to cache contract during deserialization
@@ -99,6 +102,7 @@ namespace Newtonsoft.Json.Serialization
/// Gets or sets the type of the property. /// Gets or sets the type of the property.
/// </summary> /// </summary>
/// <value>The type of the property.</value> /// <value>The type of the property.</value>
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
public Type? PropertyType public Type? PropertyType
{ {
get => _propertyType; get => _propertyType;
@@ -71,6 +71,7 @@ namespace Newtonsoft.Json.Serialization
/// Adds a <see cref="JsonProperty"/> object. /// Adds a <see cref="JsonProperty"/> object.
/// </summary> /// </summary>
/// <param name="property">The property to add to the collection.</param> /// <param name="property">The property to add to the collection.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
public void AddProperty(JsonProperty property) public void AddProperty(JsonProperty property)
{ {
MiscellaneousUtils.Assert(property.PropertyName != null); MiscellaneousUtils.Assert(property.PropertyName != null);
@@ -64,6 +64,8 @@ namespace Newtonsoft.Json.Serialization
{ {
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public void Populate(JsonReader reader, object target) public void Populate(JsonReader reader, object target)
{ {
ValidationUtils.ArgumentNotNull(target, nameof(target)); ValidationUtils.ArgumentNotNull(target, nameof(target));
@@ -139,6 +141,8 @@ namespace Newtonsoft.Json.Serialization
return Serializer._contractResolver.ResolveContract(type); return Serializer._contractResolver.ResolveContract(type);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public object? Deserialize(JsonReader reader, Type? objectType, bool checkAdditionalContent) public object? Deserialize(JsonReader reader, Type? objectType, bool checkAdditionalContent)
{ {
if (reader == null) if (reader == null)
@@ -204,6 +208,8 @@ namespace Newtonsoft.Json.Serialization
} }
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private JsonSerializerProxy GetInternalSerializer() private JsonSerializerProxy GetInternalSerializer()
{ {
if (InternalSerializer == null) if (InternalSerializer == null)
@@ -292,6 +298,8 @@ namespace Newtonsoft.Json.Serialization
} }
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private object? CreateValueInternal(JsonReader reader, Type? objectType, JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue) private object? CreateValueInternal(JsonReader reader, Type? objectType, JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue)
{ {
if (contract != null && contract.ContractType == JsonContractType.Linq) if (contract != null && contract.ContractType == JsonContractType.Linq)
@@ -424,6 +432,8 @@ namespace Newtonsoft.Json.Serialization
return converter; return converter;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private object? CreateObject(JsonReader reader, Type? objectType, JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue) private object? CreateObject(JsonReader reader, Type? objectType, JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue)
{ {
string? id; string? id;
@@ -598,6 +608,8 @@ namespace Newtonsoft.Json.Serialization
throw JsonSerializationException.Create(reader, message); throw JsonSerializationException.Create(reader, message);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type? objectType, ref JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue, out object? newValue, out string? id) private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type? objectType, ref JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue, out object? newValue, out string? id)
{ {
id = null; id = null;
@@ -685,6 +697,8 @@ namespace Newtonsoft.Json.Serialization
return false; return false;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private bool ReadMetadataProperties(JsonReader reader, ref Type? objectType, ref JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue, out object? newValue, out string? id) private bool ReadMetadataProperties(JsonReader reader, ref Type? objectType, ref JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue, out object? newValue, out string? id)
{ {
id = null; id = null;
@@ -840,6 +854,8 @@ namespace Newtonsoft.Json.Serialization
return arrayContract; return arrayContract;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private object? CreateList(JsonReader reader, Type? objectType, JsonContract? contract, JsonProperty? member, object? existingValue, string? id) private object? CreateList(JsonReader reader, Type? objectType, JsonContract? contract, JsonProperty? member, object? existingValue, string? id)
{ {
object? value; object? value;
@@ -938,6 +954,8 @@ namespace Newtonsoft.Json.Serialization
); );
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private object? EnsureType(JsonReader reader, object? value, CultureInfo culture, JsonContract? contract, Type? targetType) private object? EnsureType(JsonReader reader, object? value, CultureInfo culture, JsonContract? contract, Type? targetType)
{ {
if (targetType == null) if (targetType == null)
@@ -1009,6 +1027,8 @@ namespace Newtonsoft.Json.Serialization
return value; return value;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private bool SetPropertyValue(JsonProperty property, JsonConverter? propertyConverter, JsonContainerContract? containerContract, JsonProperty? containerProperty, JsonReader reader, object target) private bool SetPropertyValue(JsonProperty property, JsonConverter? propertyConverter, JsonContainerContract? containerContract, JsonProperty? containerProperty, JsonReader reader, object target)
{ {
bool skipSettingProperty = CalculatePropertyDetails( bool skipSettingProperty = CalculatePropertyDetails(
@@ -1215,6 +1235,7 @@ namespace Newtonsoft.Json.Serialization
return true; return true;
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private IList CreateNewList(JsonReader reader, JsonArrayContract contract, out bool createdFromNonDefaultCreator) private IList CreateNewList(JsonReader reader, JsonArrayContract contract, out bool createdFromNonDefaultCreator)
{ {
// some types like non-generic IEnumerable can be serialized but not deserialized // some types like non-generic IEnumerable can be serialized but not deserialized
@@ -1283,6 +1304,7 @@ namespace Newtonsoft.Json.Serialization
} }
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private IDictionary CreateNewDictionary(JsonReader reader, JsonDictionaryContract contract, out bool createdFromNonDefaultCreator) private IDictionary CreateNewDictionary(JsonReader reader, JsonDictionaryContract contract, out bool createdFromNonDefaultCreator)
{ {
if (contract.OverrideCreator != null) if (contract.OverrideCreator != null)
@@ -1351,6 +1373,8 @@ namespace Newtonsoft.Json.Serialization
contract.InvokeOnDeserialized(value, Serializer._context); contract.InvokeOnDeserialized(value, Serializer._context);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private object PopulateDictionary(IDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty? containerProperty, string? id) private object PopulateDictionary(IDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty? containerProperty, string? id)
{ {
object underlyingDictionary = dictionary is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : dictionary; object underlyingDictionary = dictionary is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : dictionary;
@@ -1474,6 +1498,8 @@ namespace Newtonsoft.Json.Serialization
return underlyingDictionary; return underlyingDictionary;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private object PopulateMultidimensionalArray(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty? containerProperty, string? id) private object PopulateMultidimensionalArray(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty? containerProperty, string? id)
{ {
int rank = contract.UnderlyingType.GetArrayRank(); int rank = contract.UnderlyingType.GetArrayRank();
@@ -1624,6 +1650,8 @@ namespace Newtonsoft.Json.Serialization
} }
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private object PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty? containerProperty, string? id) private object PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty? containerProperty, string? id)
{ {
#pragma warning disable CS8600, CS8602, CS8603, CS8604 #pragma warning disable CS8600, CS8602, CS8603, CS8604
@@ -1726,6 +1754,8 @@ namespace Newtonsoft.Json.Serialization
} }
#if HAVE_BINARY_SERIALIZATION #if HAVE_BINARY_SERIALIZATION
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, JsonProperty? member, string? id) private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, JsonProperty? member, string? id)
{ {
Type objectType = contract.UnderlyingType; Type objectType = contract.UnderlyingType;
@@ -1798,6 +1828,8 @@ namespace Newtonsoft.Json.Serialization
return createdObject; return createdObject;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
internal object? CreateISerializableItem(JToken token, Type type, JsonISerializableContract contract, JsonProperty? member) internal object? CreateISerializableItem(JToken token, Type type, JsonISerializableContract contract, JsonProperty? member)
{ {
JsonContract? itemContract = GetContractSafe(type); JsonContract? itemContract = GetContractSafe(type);
@@ -1822,6 +1854,8 @@ namespace Newtonsoft.Json.Serialization
#endif #endif
#if HAVE_DYNAMIC #if HAVE_DYNAMIC
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, JsonProperty? member, string? id) private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, JsonProperty? member, string? id)
{ {
IDynamicMetaObjectProvider newObject; IDynamicMetaObjectProvider newObject;
@@ -1948,6 +1982,8 @@ namespace Newtonsoft.Json.Serialization
} }
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty? containerProperty, ObjectConstructor<object> creator, string? id) private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty? containerProperty, ObjectConstructor<object> creator, string? id)
{ {
ValidationUtils.ArgumentNotNull(creator, nameof(creator)); ValidationUtils.ArgumentNotNull(creator, nameof(creator));
@@ -2182,6 +2218,8 @@ namespace Newtonsoft.Json.Serialization
return createdObject; return createdObject;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private object? DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, object? existingValue) private object? DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, object? existingValue)
{ {
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
@@ -2199,6 +2237,8 @@ namespace Newtonsoft.Json.Serialization
return value; return value;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private List<CreatorPropertyContext> ResolvePropertyAndCreatorValues(JsonObjectContract contract, JsonProperty? containerProperty, JsonReader reader, Type objectType) private List<CreatorPropertyContext> ResolvePropertyAndCreatorValues(JsonObjectContract contract, JsonProperty? containerProperty, JsonReader reader, Type objectType)
{ {
List<CreatorPropertyContext> propertyValues = new List<CreatorPropertyContext>(); List<CreatorPropertyContext> propertyValues = new List<CreatorPropertyContext>();
@@ -2298,6 +2338,8 @@ namespace Newtonsoft.Json.Serialization
return propertyValues; return propertyValues;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public object CreateNewObject(JsonReader reader, JsonObjectContract objectContract, JsonProperty? containerMember, JsonProperty? containerProperty, string? id, out bool createdFromNonDefaultCreator) public object CreateNewObject(JsonReader reader, JsonObjectContract objectContract, JsonProperty? containerMember, JsonProperty? containerProperty, string? id, out bool createdFromNonDefaultCreator)
{ {
object? newObject = null; object? newObject = null;
@@ -2341,6 +2383,8 @@ namespace Newtonsoft.Json.Serialization
return newObject; return newObject;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty? member, string? id) private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty? member, string? id)
{ {
OnDeserializing(reader, contract, newObject); OnDeserializing(reader, contract, newObject);
@@ -2509,6 +2553,8 @@ namespace Newtonsoft.Json.Serialization
return false; return false;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void SetExtensionData(JsonObjectContract contract, JsonProperty? member, JsonReader reader, string memberName, object o) private void SetExtensionData(JsonObjectContract contract, JsonProperty? member, JsonReader reader, string memberName, object o)
{ {
if (contract.ExtensionDataSetter != null) if (contract.ExtensionDataSetter != null)
@@ -2530,6 +2576,8 @@ namespace Newtonsoft.Json.Serialization
} }
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private object? ReadExtensionDataValue(JsonObjectContract contract, JsonProperty? member, JsonReader reader) private object? ReadExtensionDataValue(JsonObjectContract contract, JsonProperty? member, JsonReader reader)
{ {
object? value; object? value;
@@ -2544,6 +2592,8 @@ namespace Newtonsoft.Json.Serialization
return value; return value;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void EndProcessProperty(object newObject, JsonReader reader, JsonObjectContract contract, int initialDepth, JsonProperty property, PropertyPresence presence, bool setDefaultValue) private void EndProcessProperty(object newObject, JsonReader reader, JsonObjectContract contract, int initialDepth, JsonProperty property, PropertyPresence presence, bool setDefaultValue)
{ {
if (presence == PropertyPresence.None || presence == PropertyPresence.Null) if (presence == PropertyPresence.None || presence == PropertyPresence.Null)
@@ -58,6 +58,8 @@ namespace Newtonsoft.Json.Serialization
{ {
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType) public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType)
{ {
if (jsonWriter == null) if (jsonWriter == null)
@@ -104,6 +106,8 @@ namespace Newtonsoft.Json.Serialization
} }
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private JsonSerializerProxy GetInternalSerializer() private JsonSerializerProxy GetInternalSerializer()
{ {
if (InternalSerializer == null) if (InternalSerializer == null)
@@ -151,6 +155,8 @@ namespace Newtonsoft.Json.Serialization
JsonWriter.WriteValue(writer, contract.TypeCode, value); JsonWriter.WriteValue(writer, contract.TypeCode, value);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void SerializeValue(JsonWriter writer, object? value, JsonContract? valueContract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerProperty) private void SerializeValue(JsonWriter writer, object? value, JsonContract? valueContract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerProperty)
{ {
if (value == null) if (value == null)
@@ -394,6 +400,7 @@ namespace Newtonsoft.Json.Serialization
} }
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
internal static bool TryConvertToString(object value, Type type, [NotNullWhen(true)]out string? s) internal static bool TryConvertToString(object value, Type type, [NotNullWhen(true)]out string? s)
{ {
#if HAVE_DATE_ONLY #if HAVE_DATE_ONLY
@@ -435,6 +442,7 @@ namespace Newtonsoft.Json.Serialization
return false; return false;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
private void SerializeString(JsonWriter writer, object value, JsonStringContract contract) private void SerializeString(JsonWriter writer, object value, JsonStringContract contract)
{ {
OnSerializing(writer, contract, value); OnSerializing(writer, contract, value);
@@ -465,6 +473,8 @@ namespace Newtonsoft.Json.Serialization
contract.InvokeOnSerialized(value, Serializer._context); contract.InvokeOnSerialized(value, Serializer._context);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty)
{ {
OnSerializing(writer, contract, value); OnSerializing(writer, contract, value);
@@ -659,6 +669,8 @@ namespace Newtonsoft.Json.Serialization
return ((value & flag) == flag); return ((value & flag) == flag);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract? collectionContract, JsonProperty? containerProperty) private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract? collectionContract, JsonProperty? containerProperty)
{ {
if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty)) if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty))
@@ -690,6 +702,8 @@ namespace Newtonsoft.Json.Serialization
} }
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty)
{ {
object underlyingList = values is IWrappedCollection wrappedCollection ? wrappedCollection.UnderlyingCollection : values; object underlyingList = values is IWrappedCollection wrappedCollection ? wrappedCollection.UnderlyingCollection : values;
@@ -753,6 +767,8 @@ namespace Newtonsoft.Json.Serialization
OnSerialized(writer, contract, underlyingList); OnSerialized(writer, contract, underlyingList);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty)
{ {
OnSerializing(writer, contract, values); OnSerializing(writer, contract, values);
@@ -773,6 +789,8 @@ namespace Newtonsoft.Json.Serialization
OnSerialized(writer, contract, values); OnSerialized(writer, contract, values);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty? member, int initialDepth, int[] indices) private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty? member, int initialDepth, int[] indices)
{ {
int dimension = indices.Length; int dimension = indices.Length;
@@ -866,6 +884,8 @@ namespace Newtonsoft.Json.Serialization
#if HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE #if HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE
[SecuritySafeCritical] [SecuritySafeCritical]
#endif #endif
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty)
{ {
if (!JsonTypeReflector.FullyTrusted) if (!JsonTypeReflector.FullyTrusted)
@@ -909,6 +929,8 @@ namespace Newtonsoft.Json.Serialization
#endif #endif
#if HAVE_DYNAMIC #if HAVE_DYNAMIC
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty)
{ {
OnSerializing(writer, contract, value); OnSerializing(writer, contract, value);
@@ -993,6 +1015,7 @@ namespace Newtonsoft.Json.Serialization
} }
#endif #endif
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
private bool ShouldWriteDynamicProperty(object? memberValue) private bool ShouldWriteDynamicProperty(object? memberValue)
{ {
if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null) if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null)
@@ -1053,6 +1076,8 @@ namespace Newtonsoft.Json.Serialization
return false; return false;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty)
{ {
#pragma warning disable CS8600, CS8602, CS8604 #pragma warning disable CS8600, CS8602, CS8604
@@ -1137,6 +1162,7 @@ namespace Newtonsoft.Json.Serialization
#pragma warning restore CS8600, CS8602, CS8604 #pragma warning restore CS8600, CS8602, CS8604
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape) private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape)
{ {
if (contract.ContractType == JsonContractType.Primitive) if (contract.ContractType == JsonContractType.Primitive)
@@ -25,6 +25,7 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
@@ -32,6 +33,8 @@ using System.Runtime.Serialization;
namespace Newtonsoft.Json.Serialization namespace Newtonsoft.Json.Serialization
{ {
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
internal class JsonSerializerProxy : JsonSerializer internal class JsonSerializerProxy : JsonSerializer
{ {
private readonly JsonSerializerInternalReader? _serializerReader; private readonly JsonSerializerInternalReader? _serializerReader;
@@ -24,6 +24,8 @@
#endregion #endregion
using System; using System;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization namespace Newtonsoft.Json.Serialization
{ {
@@ -36,6 +38,7 @@ namespace Newtonsoft.Json.Serialization
/// Initializes a new instance of the <see cref="JsonStringContract"/> class. /// Initializes a new instance of the <see cref="JsonStringContract"/> class.
/// </summary> /// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param> /// <param name="underlyingType">The underlying type for the contract.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
public JsonStringContract(Type underlyingType) public JsonStringContract(Type underlyingType)
: base(underlyingType) : base(underlyingType)
{ {
@@ -34,6 +34,8 @@ using System.Security.Permissions;
#endif #endif
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
#if !HAVE_LINQ #if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge; using Newtonsoft.Json.Utilities.LinqBridge;
#else #else
@@ -59,20 +61,34 @@ namespace Newtonsoft.Json.Serialization
public const string ConcurrentDictionaryTypeName = "System.Collections.Concurrent.ConcurrentDictionary`2"; public const string ConcurrentDictionaryTypeName = "System.Collections.Concurrent.ConcurrentDictionary`2";
private static readonly ThreadSafeStore<Type, Func<object[]?, object>> CreatorCache = [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
new ThreadSafeStore<Type, Func<object[]?, object>>(GetCreator); [RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static class CreatorCache
{
internal static readonly ThreadSafeStore<Type, Func<object[]?, object>> Instance =
new ThreadSafeStore<Type, Func<object[]?, object>>(GetCreator);
}
#if !(NET20 || DOTNET) #if !(NET20 || DOTNET)
private static readonly ThreadSafeStore<Type, Type?> AssociatedMetadataTypesCache = new ThreadSafeStore<Type, Type?>(GetAssociateMetadataTypeFromAttribute); [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static class AssociatedMetadataTypesCache
{
internal static readonly ThreadSafeStore<Type, Type?> Instance = new ThreadSafeStore<Type, Type?>(GetAssociateMetadataTypeFromAttribute);
}
private static ReflectionObject? _metadataTypeAttributeReflectionObject; private static ReflectionObject? _metadataTypeAttributeReflectionObject;
#endif #endif
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static T? GetCachedAttribute<T>(object attributeProvider) where T : Attribute public static T? GetCachedAttribute<T>(object attributeProvider) where T : Attribute
{ {
return CachedAttributeGetter<T>.GetAttribute(attributeProvider); return CachedAttributeGetter<T>.GetAttribute(attributeProvider);
} }
#if HAVE_TYPE_DESCRIPTOR #if HAVE_TYPE_DESCRIPTOR
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
public static bool CanTypeDescriptorConvertString(Type type, out TypeConverter typeConverter) public static bool CanTypeDescriptorConvertString(Type type, out TypeConverter typeConverter)
{ {
typeConverter = TypeDescriptor.GetConverter(type); typeConverter = TypeDescriptor.GetConverter(type);
@@ -85,7 +101,7 @@ namespace Newtonsoft.Json.Serialization
if (!string.Equals(converterType.FullName, "System.ComponentModel.ComponentConverter", StringComparison.Ordinal) if (!string.Equals(converterType.FullName, "System.ComponentModel.ComponentConverter", StringComparison.Ordinal)
&& !string.Equals(converterType.FullName, "System.ComponentModel.ReferenceConverter", StringComparison.Ordinal) && !string.Equals(converterType.FullName, "System.ComponentModel.ReferenceConverter", StringComparison.Ordinal)
&& !string.Equals(converterType.FullName, "System.Windows.Forms.Design.DataSourceConverter", StringComparison.Ordinal) && !string.Equals(converterType.FullName, "System.Windows.Forms.Design.DataSourceConverter", StringComparison.Ordinal)
&& converterType != typeof(TypeConverter)) && converterType != typeof(TypeConverter))
{ {
return typeConverter.CanConvertTo(typeof(string)); return typeConverter.CanConvertTo(typeof(string));
} }
@@ -97,6 +113,8 @@ namespace Newtonsoft.Json.Serialization
#endif #endif
#if HAVE_DATA_CONTRACTS #if HAVE_DATA_CONTRACTS
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static DataContractAttribute? GetDataContractAttribute(Type type) public static DataContractAttribute? GetDataContractAttribute(Type type)
{ {
// DataContractAttribute does not have inheritance // DataContractAttribute does not have inheritance
@@ -116,6 +134,8 @@ namespace Newtonsoft.Json.Serialization
return null; return null;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static DataMemberAttribute? GetDataMemberAttribute(MemberInfo memberInfo) public static DataMemberAttribute? GetDataMemberAttribute(MemberInfo memberInfo)
{ {
// DataMemberAttribute does not have inheritance // DataMemberAttribute does not have inheritance
@@ -152,6 +172,8 @@ namespace Newtonsoft.Json.Serialization
} }
#endif #endif
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute) public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute)
{ {
JsonObjectAttribute? objectAttribute = GetCachedAttribute<JsonObjectAttribute>(objectType); JsonObjectAttribute? objectAttribute = GetCachedAttribute<JsonObjectAttribute>(objectType);
@@ -179,13 +201,15 @@ namespace Newtonsoft.Json.Serialization
return MemberSerialization.OptOut; return MemberSerialization.OptOut;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static JsonConverter? GetJsonConverter(object attributeProvider) public static JsonConverter? GetJsonConverter(object attributeProvider)
{ {
JsonConverterAttribute? converterAttribute = GetCachedAttribute<JsonConverterAttribute>(attributeProvider); JsonConverterAttribute? converterAttribute = GetCachedAttribute<JsonConverterAttribute>(attributeProvider);
if (converterAttribute != null) if (converterAttribute != null)
{ {
Func<object[]?, object> creator = CreatorCache.Get(converterAttribute.ConverterType); Func<object[]?, object> creator = CreatorCache.Instance.Get(converterAttribute.ConverterType);
if (creator != null) if (creator != null)
{ {
return (JsonConverter)creator(converterAttribute.ConverterParameters); return (JsonConverter)creator(converterAttribute.ConverterParameters);
@@ -201,18 +225,24 @@ namespace Newtonsoft.Json.Serialization
/// <param name="converterType">The <see cref="JsonConverter"/> type to create.</param> /// <param name="converterType">The <see cref="JsonConverter"/> type to create.</param>
/// <param name="args">Optional arguments to pass to an initializing constructor of the JsonConverter. /// <param name="args">Optional arguments to pass to an initializing constructor of the JsonConverter.
/// If <c>null</c>, the default constructor is used.</param> /// If <c>null</c>, the default constructor is used.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static JsonConverter CreateJsonConverterInstance(Type converterType, object[]? args) public static JsonConverter CreateJsonConverterInstance(Type converterType, object[]? args)
{ {
Func<object[]?, object> converterCreator = CreatorCache.Get(converterType); Func<object[]?, object> converterCreator = CreatorCache.Instance.Get(converterType);
return (JsonConverter)converterCreator(args); return (JsonConverter)converterCreator(args);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static NamingStrategy CreateNamingStrategyInstance(Type namingStrategyType, object[]? args) public static NamingStrategy CreateNamingStrategyInstance(Type namingStrategyType, object[]? args)
{ {
Func<object[]?, object> converterCreator = CreatorCache.Get(namingStrategyType); Func<object[]?, object> converterCreator = CreatorCache.Instance.Get(namingStrategyType);
return (NamingStrategy)converterCreator(args); return (NamingStrategy)converterCreator(args);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static NamingStrategy? GetContainerNamingStrategy(JsonContainerAttribute containerAttribute) public static NamingStrategy? GetContainerNamingStrategy(JsonContainerAttribute containerAttribute)
{ {
if (containerAttribute.NamingStrategyInstance == null) if (containerAttribute.NamingStrategyInstance == null)
@@ -228,7 +258,10 @@ namespace Newtonsoft.Json.Serialization
return containerAttribute.NamingStrategyInstance; return containerAttribute.NamingStrategyInstance;
} }
private static Func<object[]?, object> GetCreator(Type type) [RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static Func<object[]?, object> GetCreator(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
Type type)
{ {
Func<object>? defaultConstructor = (ReflectionUtils.HasDefaultConstructor(type, false)) Func<object>? defaultConstructor = (ReflectionUtils.HasDefaultConstructor(type, false))
? ReflectionDelegateFactory.CreateDefaultConstructor<object>(type) ? ReflectionDelegateFactory.CreateDefaultConstructor<object>(type)
@@ -277,11 +310,15 @@ namespace Newtonsoft.Json.Serialization
} }
#if !(NET20 || DOTNET) #if !(NET20 || DOTNET)
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static Type? GetAssociatedMetadataType(Type type) private static Type? GetAssociatedMetadataType(Type type)
{ {
return AssociatedMetadataTypesCache.Get(type); return AssociatedMetadataTypesCache.Instance.Get(type);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static Type? GetAssociateMetadataTypeFromAttribute(Type type) private static Type? GetAssociateMetadataTypeFromAttribute(Type type)
{ {
Attribute[] customAttributes = ReflectionUtils.GetAttributes(type, null, true); Attribute[] customAttributes = ReflectionUtils.GetAttributes(type, null, true);
@@ -309,7 +346,9 @@ namespace Newtonsoft.Json.Serialization
} }
#endif #endif
private static T? GetAttribute<T>(Type type) where T : Attribute [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static T? GetAttribute<T>([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] Type type) where T : Attribute
{ {
T? attribute; T? attribute;
@@ -343,6 +382,8 @@ namespace Newtonsoft.Json.Serialization
return null; return null;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static T? GetAttribute<T>(MemberInfo memberInfo) where T : Attribute private static T? GetAttribute<T>(MemberInfo memberInfo) where T : Attribute
{ {
T? attribute; T? attribute;
@@ -424,6 +465,8 @@ namespace Newtonsoft.Json.Serialization
} }
#endif #endif
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static T? GetAttribute<T>(object provider) where T : Attribute public static T? GetAttribute<T>(object provider) where T : Attribute
{ {
if (provider is Type type) if (provider is Type type)
@@ -26,6 +26,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Collections; using System.Collections;
@@ -94,6 +95,7 @@ namespace Newtonsoft.Json.Utilities
} }
#endif #endif
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
public static bool IsDictionaryType(Type type) public static bool IsDictionaryType(Type type)
{ {
ValidationUtils.ArgumentNotNull(type, nameof(type)); ValidationUtils.ArgumentNotNull(type, nameof(type));
@@ -116,14 +118,23 @@ namespace Newtonsoft.Json.Utilities
return false; return false;
} }
public static ConstructorInfo? ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType) [RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static ConstructorInfo? ResolveEnumerableCollectionConstructor(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
Type collectionType,
Type collectionItemType)
{ {
Type genericConstructorArgument = typeof(IList<>).MakeGenericType(collectionItemType); Type genericConstructorArgument = typeof(IList<>).MakeGenericType(collectionItemType);
return ResolveEnumerableCollectionConstructor(collectionType, collectionItemType, genericConstructorArgument); return ResolveEnumerableCollectionConstructor(collectionType, collectionItemType, genericConstructorArgument);
} }
public static ConstructorInfo? ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType, Type constructorArgumentType) [RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static ConstructorInfo? ResolveEnumerableCollectionConstructor(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
Type collectionType,
Type collectionItemType,
Type constructorArgumentType)
{ {
Type genericEnumerable = typeof(IEnumerable<>).MakeGenericType(collectionItemType); Type genericEnumerable = typeof(IEnumerable<>).MakeGenericType(collectionItemType);
ConstructorInfo? match = null; ConstructorInfo? match = null;
@@ -351,6 +362,7 @@ namespace Newtonsoft.Json.Utilities
return currentList; return currentList;
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static Array ToMultidimensionalArray(IList values, Type type, int rank) public static Array ToMultidimensionalArray(IList values, Type type, int rank)
{ {
IList<int> dimensions = GetDimensions(values, rank); IList<int> dimensions = GetDimensions(values, rank);
+21 -3
View File
@@ -198,6 +198,7 @@ namespace Newtonsoft.Json.Utilities
return GetTypeCode(t, out _); return GetTypeCode(t, out _);
} }
[UnconditionalSuppressMessage("AotAnalysis", "IL3050", Justification = "Nullable<T> instantiated over primitive types are kept by TypeCodeMap")]
public static PrimitiveTypeCode GetTypeCode(Type t, out bool isEnum) public static PrimitiveTypeCode GetTypeCode(Type t, out bool isEnum)
{ {
if (TypeCodeMap.TryGetValue(t, out PrimitiveTypeCode typeCode)) if (TypeCodeMap.TryGetValue(t, out PrimitiveTypeCode typeCode))
@@ -256,9 +257,16 @@ namespace Newtonsoft.Json.Utilities
#endif #endif
} }
private static readonly ThreadSafeStore<StructMultiKey<Type, Type>, Func<object?, object?>?> CastConverters = [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
new ThreadSafeStore<StructMultiKey<Type, Type>, Func<object?, object?>?>(CreateCastConverter); [RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
static class CastConverters
{
public static readonly ThreadSafeStore<StructMultiKey<Type, Type>, Func<object?, object?>?> Instance =
new ThreadSafeStore<StructMultiKey<Type, Type>, Func<object?, object?>?>(CreateCastConverter);
}
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static Func<object?, object?>? CreateCastConverter(StructMultiKey<Type, Type> t) private static Func<object?, object?>? CreateCastConverter(StructMultiKey<Type, Type> t)
{ {
Type initialType = t.Value1; Type initialType = t.Value1;
@@ -369,6 +377,8 @@ namespace Newtonsoft.Json.Utilities
NoValidConversion = 3 NoValidConversion = 3
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static object Convert(object initialValue, CultureInfo culture, Type targetType) public static object Convert(object initialValue, CultureInfo culture, Type targetType)
{ {
switch (TryConvertInternal(initialValue, culture, targetType, out object? value)) switch (TryConvertInternal(initialValue, culture, targetType, out object? value))
@@ -386,6 +396,8 @@ namespace Newtonsoft.Json.Utilities
} }
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static bool TryConvert(object? initialValue, CultureInfo culture, Type targetType, out object? value) private static bool TryConvert(object? initialValue, CultureInfo culture, Type targetType, out object? value)
{ {
try try
@@ -405,6 +417,8 @@ namespace Newtonsoft.Json.Utilities
} }
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static ConvertResult TryConvertInternal(object? initialValue, CultureInfo culture, Type targetType, out object? value) private static ConvertResult TryConvertInternal(object? initialValue, CultureInfo culture, Type targetType, out object? value)
{ {
if (initialValue == null) if (initialValue == null)
@@ -587,6 +601,8 @@ namespace Newtonsoft.Json.Utilities
/// The converted type. If conversion was unsuccessful, the initial value /// The converted type. If conversion was unsuccessful, the initial value
/// is returned if assignable to the target type. /// is returned if assignable to the target type.
/// </returns> /// </returns>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static object? ConvertOrCast(object? initialValue, CultureInfo culture, Type targetType) public static object? ConvertOrCast(object? initialValue, CultureInfo culture, Type targetType)
{ {
if (targetType == typeof(object)) if (targetType == typeof(object))
@@ -607,6 +623,8 @@ namespace Newtonsoft.Json.Utilities
return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue)!, targetType); return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue)!, targetType);
} }
#endregion #endregion
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static object? EnsureTypeAssignable(object? value, Type initialType, Type targetType) private static object? EnsureTypeAssignable(object? value, Type initialType, Type targetType)
{ {
@@ -619,7 +637,7 @@ namespace Newtonsoft.Json.Utilities
return value; return value;
} }
Func<object?, object?>? castConverter = CastConverters.Get(new StructMultiKey<Type, Type>(valueType, targetType)); Func<object?, object?>? castConverter = CastConverters.Instance.Get(new StructMultiKey<Type, Type>(valueType, targetType));
if (castConverter != null) if (castConverter != null)
{ {
return castConverter(value); return castConverter(value);
@@ -25,6 +25,7 @@
#if HAVE_DYNAMIC #if HAVE_DYNAMIC
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic; using System.Dynamic;
namespace Newtonsoft.Json.Utilities namespace Newtonsoft.Json.Utilities
@@ -42,6 +43,7 @@ namespace Newtonsoft.Json.Utilities
return false; return false;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
public virtual bool TryConvert(T instance, ConvertBinder binder, out object? result) public virtual bool TryConvert(T instance, ConvertBinder binder, out object? result)
{ {
result = null; result = null;
@@ -1,4 +1,4 @@
#region License #region License
// Copyright (c) 2007 James Newton-King // Copyright (c) 2007 James Newton-King
// //
// Permission is hereby granted, free of charge, to any person // Permission is hereby granted, free of charge, to any person
@@ -26,12 +26,15 @@
#if HAVE_DYNAMIC #if HAVE_DYNAMIC
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic; using System.Dynamic;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
namespace Newtonsoft.Json.Utilities namespace Newtonsoft.Json.Utilities
{ {
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
internal sealed class DynamicProxyMetaObject<T> : DynamicMetaObject internal sealed class DynamicProxyMetaObject<T> : DynamicMetaObject
{ {
private readonly DynamicProxy<T> _proxy; private readonly DynamicProxy<T> _proxy;
@@ -373,6 +376,7 @@ namespace Newtonsoft.Json.Utilities
// is only used by DynamicObject.GetMember--it is not expected to // is only used by DynamicObject.GetMember--it is not expected to
// (and cannot) implement binding semantics. It is just so the DO // (and cannot) implement binding semantics. It is just so the DO
// can use the Name and IgnoreCase properties. // can use the Name and IgnoreCase properties.
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private sealed class GetBinderAdapter : GetMemberBinder private sealed class GetBinderAdapter : GetMemberBinder
{ {
internal GetBinderAdapter(InvokeMemberBinder binder) : internal GetBinderAdapter(InvokeMemberBinder binder) :
@@ -26,6 +26,7 @@
#if HAVE_REFLECTION_EMIT #if HAVE_REFLECTION_EMIT
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#if !HAVE_LINQ #if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge; using Newtonsoft.Json.Utilities.LinqBridge;
#endif #endif
@@ -40,6 +41,7 @@ namespace Newtonsoft.Json.Utilities
{ {
internal static DynamicReflectionDelegateFactory Instance { get; } = new DynamicReflectionDelegateFactory(); internal static DynamicReflectionDelegateFactory Instance { get; } = new DynamicReflectionDelegateFactory();
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static DynamicMethod CreateDynamicMethod(string name, Type? returnType, Type[] parameterTypes, Type owner) private static DynamicMethod CreateDynamicMethod(string name, Type? returnType, Type[] parameterTypes, Type owner)
{ {
DynamicMethod dynamicMethod = !owner.IsInterface() DynamicMethod dynamicMethod = !owner.IsInterface()
@@ -49,6 +51,7 @@ namespace Newtonsoft.Json.Utilities
return dynamicMethod; return dynamicMethod;
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method) public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
{ {
DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString()!, typeof(object), new[] { typeof(object[]) }, method.DeclaringType!); DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString()!, typeof(object), new[] { typeof(object[]) }, method.DeclaringType!);
@@ -59,6 +62,7 @@ namespace Newtonsoft.Json.Utilities
return (ObjectConstructor<object>)dynamicMethod.CreateDelegate(typeof(ObjectConstructor<object>)); return (ObjectConstructor<object>)dynamicMethod.CreateDelegate(typeof(ObjectConstructor<object>));
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override MethodCall<T, object?> CreateMethodCall<T>(MethodBase method) public override MethodCall<T, object?> CreateMethodCall<T>(MethodBase method)
{ {
DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString()!, typeof(object), new[] { typeof(object), typeof(object[]) }, method.DeclaringType!); DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString()!, typeof(object), new[] { typeof(object), typeof(object[]) }, method.DeclaringType!);
@@ -242,7 +246,10 @@ namespace Newtonsoft.Json.Utilities
generator.Return(); generator.Return();
} }
public override Func<T> CreateDefaultConstructor<T>(Type type) [RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Func<T> CreateDefaultConstructor<T>(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
Type type)
{ {
DynamicMethod dynamicMethod = CreateDynamicMethod("Create" + type.FullName, typeof(T), ReflectionUtils.EmptyTypes, type); DynamicMethod dynamicMethod = CreateDynamicMethod("Create" + type.FullName, typeof(T), ReflectionUtils.EmptyTypes, type);
dynamicMethod.InitLocals = true; dynamicMethod.InitLocals = true;
@@ -253,7 +260,11 @@ namespace Newtonsoft.Json.Utilities
return (Func<T>)dynamicMethod.CreateDelegate(typeof(Func<T>)); return (Func<T>)dynamicMethod.CreateDelegate(typeof(Func<T>));
} }
private void GenerateCreateDefaultConstructorIL(Type type, ILGenerator generator, Type delegateType) private void GenerateCreateDefaultConstructorIL(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
Type type,
ILGenerator generator,
Type delegateType)
{ {
if (type.IsValueType()) if (type.IsValueType())
{ {
@@ -282,6 +293,7 @@ namespace Newtonsoft.Json.Utilities
generator.Return(); generator.Return();
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Func<T, object?> CreateGet<T>(PropertyInfo propertyInfo) public override Func<T, object?> CreateGet<T>(PropertyInfo propertyInfo)
{ {
DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + propertyInfo.Name, typeof(object), new[] { typeof(T) }, propertyInfo.DeclaringType!); DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + propertyInfo.Name, typeof(object), new[] { typeof(T) }, propertyInfo.DeclaringType!);
@@ -310,6 +322,7 @@ namespace Newtonsoft.Json.Utilities
generator.Return(); generator.Return();
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Func<T, object?> CreateGet<T>(FieldInfo fieldInfo) public override Func<T, object?> CreateGet<T>(FieldInfo fieldInfo)
{ {
if (fieldInfo.IsLiteral) if (fieldInfo.IsLiteral)
@@ -343,6 +356,7 @@ namespace Newtonsoft.Json.Utilities
generator.Return(); generator.Return();
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Action<T, object?> CreateSet<T>(FieldInfo fieldInfo) public override Action<T, object?> CreateSet<T>(FieldInfo fieldInfo)
{ {
DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(T), typeof(object) }, fieldInfo.DeclaringType!); DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(T), typeof(object) }, fieldInfo.DeclaringType!);
@@ -375,6 +389,7 @@ namespace Newtonsoft.Json.Utilities
generator.Return(); generator.Return();
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Action<T, object?> CreateSet<T>(PropertyInfo propertyInfo) public override Action<T, object?> CreateSet<T>(PropertyInfo propertyInfo)
{ {
DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + propertyInfo.Name, null, new[] { typeof(T), typeof(object) }, propertyInfo.DeclaringType!); DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + propertyInfo.Name, null, new[] { typeof(T), typeof(object) }, propertyInfo.DeclaringType!);
@@ -39,6 +39,7 @@ using System.Text;
using System.Globalization; using System.Globalization;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using System.Diagnostics; using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace Newtonsoft.Json.Utilities namespace Newtonsoft.Json.Utilities
{ {
@@ -60,6 +61,8 @@ namespace Newtonsoft.Json.Utilities
private static MethodCall<object?, object?>? _setMemberCall; private static MethodCall<object?, object?>? _setMemberCall;
private static bool _init; private static bool _init;
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static void Init() private static void Init()
{ {
if (!_init) if (!_init)
@@ -80,6 +83,7 @@ namespace Newtonsoft.Json.Utilities
} }
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static object CreateSharpArgumentInfoArray(params int[] values) private static object CreateSharpArgumentInfoArray(params int[] values)
{ {
Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true)!; Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true)!;
@@ -97,6 +101,8 @@ namespace Newtonsoft.Json.Utilities
return a; return a;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static void CreateMemberCalls() private static void CreateMemberCalls()
{ {
Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true)!; Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true)!;
@@ -113,6 +119,8 @@ namespace Newtonsoft.Json.Utilities
} }
#endif #endif
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static CallSiteBinder GetMember(string name, Type context) public static CallSiteBinder GetMember(string name, Type context)
{ {
#if !HAVE_REFLECTION_BINDER #if !HAVE_REFLECTION_BINDER
@@ -126,6 +134,8 @@ namespace Newtonsoft.Json.Utilities
#endif #endif
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static CallSiteBinder SetMember(string name, Type context) public static CallSiteBinder SetMember(string name, Type context)
{ {
#if !HAVE_REFLECTION_BINDER #if !HAVE_REFLECTION_BINDER
@@ -151,6 +161,7 @@ namespace Newtonsoft.Json.Utilities
} }
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
internal class NoThrowGetBinderMember : GetMemberBinder internal class NoThrowGetBinderMember : GetMemberBinder
{ {
private readonly GetMemberBinder _innerBinder; private readonly GetMemberBinder _innerBinder;
@@ -173,6 +184,7 @@ namespace Newtonsoft.Json.Utilities
} }
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
internal class NoThrowSetBinderMember : SetMemberBinder internal class NoThrowSetBinderMember : SetMemberBinder
{ {
private readonly SetMemberBinder _innerBinder; private readonly SetMemberBinder _innerBinder;
@@ -0,0 +1,99 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#if !NET5_0_OR_GREATER
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>
/// Specifies the types of members that are dynamically accessed.
///
/// This enumeration has a <see cref="FlagsAttribute"/> attribute that allows a
/// bitwise combination of its member values.
/// </summary>
[Flags]
internal enum DynamicallyAccessedMemberTypes
{
/// <summary>
/// Specifies no members.
/// </summary>
None = 0,
/// <summary>
/// Specifies the default, parameterless public constructor.
/// </summary>
PublicParameterlessConstructor = 0x0001,
/// <summary>
/// Specifies all public constructors.
/// </summary>
PublicConstructors = 0x0002 | PublicParameterlessConstructor,
/// <summary>
/// Specifies all non-public constructors.
/// </summary>
NonPublicConstructors = 0x0004,
/// <summary>
/// Specifies all public methods.
/// </summary>
PublicMethods = 0x0008,
/// <summary>
/// Specifies all non-public methods.
/// </summary>
NonPublicMethods = 0x0010,
/// <summary>
/// Specifies all public fields.
/// </summary>
PublicFields = 0x0020,
/// <summary>
/// Specifies all non-public fields.
/// </summary>
NonPublicFields = 0x0040,
/// <summary>
/// Specifies all public nested types.
/// </summary>
PublicNestedTypes = 0x0080,
/// <summary>
/// Specifies all non-public nested types.
/// </summary>
NonPublicNestedTypes = 0x0100,
/// <summary>
/// Specifies all public properties.
/// </summary>
PublicProperties = 0x0200,
/// <summary>
/// Specifies all non-public properties.
/// </summary>
NonPublicProperties = 0x0400,
/// <summary>
/// Specifies all public events.
/// </summary>
PublicEvents = 0x0800,
/// <summary>
/// Specifies all non-public events.
/// </summary>
NonPublicEvents = 0x1000,
/// <summary>
/// Specifies all interfaces implemented by the type.
/// </summary>
Interfaces = 0x2000,
/// <summary>
/// Specifies all members.
/// </summary>
All = ~None
}
}
#endif // !NET5_0_OR_GREATER
@@ -0,0 +1,55 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#if !NET5_0_OR_GREATER
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>
/// Indicates that certain members on a specified <see cref="Type"/> are accessed dynamically,
/// for example through <see cref="Reflection"/>.
/// </summary>
/// <remarks>
/// This allows tools to understand which members are being accessed during the execution
/// of a program.
///
/// This attribute is valid on members whose type is <see cref="Type"/> or <see cref="string"/>.
///
/// When this attribute is applied to a location of type <see cref="string"/>, the assumption is
/// that the string represents a fully qualified type name.
///
/// When this attribute is applied to a class, interface, or struct, the members specified
/// can be accessed dynamically on <see cref="Type"/> instances returned from calling
/// <see cref="object.GetType"/> on instances of that class, interface, or struct.
///
/// If the attribute is applied to a method it's treated as a special case and it implies
/// the attribute should be applied to the "this" parameter of the method. As such the attribute
/// should only be used on instance methods of types assignable to System.Type (or string, but no methods
/// will use it there).
/// </remarks>
[AttributeUsage(
AttributeTargets.Field | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter |
AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Method |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct,
Inherited = false)]
internal sealed class DynamicallyAccessedMembersAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="DynamicallyAccessedMembersAttribute"/> class
/// with the specified member types.
/// </summary>
/// <param name="memberTypes">The types of members dynamically accessed.</param>
public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)
{
MemberTypes = memberTypes;
}
/// <summary>
/// Gets the <see cref="DynamicallyAccessedMemberTypes"/> which specifies the type
/// of members dynamically accessed.
/// </summary>
public DynamicallyAccessedMemberTypes MemberTypes { get; }
}
}
#endif // !NET5_0_OR_GREATER
@@ -48,6 +48,7 @@ namespace Newtonsoft.Json.Utilities
private static readonly ThreadSafeStore<StructMultiKey<Type, NamingStrategy?>, EnumInfo> ValuesAndNamesPerEnum = new ThreadSafeStore<StructMultiKey<Type, NamingStrategy?>, EnumInfo>(InitializeValuesAndNames); private static readonly ThreadSafeStore<StructMultiKey<Type, NamingStrategy?>, EnumInfo> ValuesAndNamesPerEnum = new ThreadSafeStore<StructMultiKey<Type, NamingStrategy?>, EnumInfo>(InitializeValuesAndNames);
[UnconditionalSuppressMessage("TrimAnalysis", "IL2080", Justification = "Enum fields are not trimmed")]
private static EnumInfo InitializeValuesAndNames(StructMultiKey<Type, NamingStrategy?> key) private static EnumInfo InitializeValuesAndNames(StructMultiKey<Type, NamingStrategy?> key)
{ {
Type enumType = key.Value1; Type enumType = key.Value1;
@@ -26,6 +26,7 @@
#if !(NET20 || NET35) #if !(NET20 || NET35)
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System; using System;
@@ -41,6 +42,7 @@ namespace Newtonsoft.Json.Utilities
internal static ReflectionDelegateFactory Instance => _instance; internal static ReflectionDelegateFactory Instance => _instance;
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method) public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
{ {
ValidationUtils.ArgumentNotNull(method, nameof(method)); ValidationUtils.ArgumentNotNull(method, nameof(method));
@@ -57,6 +59,7 @@ namespace Newtonsoft.Json.Utilities
return compiled; return compiled;
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override MethodCall<T, object?> CreateMethodCall<T>(MethodBase method) public override MethodCall<T, object?> CreateMethodCall<T>(MethodBase method)
{ {
ValidationUtils.ArgumentNotNull(method, nameof(method)); ValidationUtils.ArgumentNotNull(method, nameof(method));
@@ -187,7 +190,10 @@ namespace Newtonsoft.Json.Utilities
return callExpression; return callExpression;
} }
public override Func<T> CreateDefaultConstructor<T>(Type type) [RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Func<T> CreateDefaultConstructor<T>(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
Type type)
{ {
ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(type, "type");
@@ -218,6 +224,7 @@ namespace Newtonsoft.Json.Utilities
} }
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Func<T, object?> CreateGet<T>(PropertyInfo propertyInfo) public override Func<T, object?> CreateGet<T>(PropertyInfo propertyInfo)
{ {
ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo));
@@ -253,6 +260,7 @@ namespace Newtonsoft.Json.Utilities
return compiled; return compiled;
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Func<T, object?> CreateGet<T>(FieldInfo fieldInfo) public override Func<T, object?> CreateGet<T>(FieldInfo fieldInfo)
{ {
ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo));
@@ -277,6 +285,7 @@ namespace Newtonsoft.Json.Utilities
return compiled; return compiled;
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Action<T, object?> CreateSet<T>(FieldInfo fieldInfo) public override Action<T, object?> CreateSet<T>(FieldInfo fieldInfo)
{ {
ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo));
@@ -313,6 +322,7 @@ namespace Newtonsoft.Json.Utilities
return compiled; return compiled;
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Action<T, object?> CreateSet<T>(PropertyInfo propertyInfo) public override Action<T, object?> CreateSet<T>(PropertyInfo propertyInfo)
{ {
ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo));
+20 -1
View File
@@ -32,6 +32,7 @@ using System.Reflection;
using System.Text; using System.Text;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using System.Diagnostics; using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace Newtonsoft.Json.Utilities namespace Newtonsoft.Json.Utilities
{ {
@@ -56,6 +57,8 @@ namespace Newtonsoft.Json.Utilities
internal class FSharpUtils internal class FSharpUtils
{ {
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private FSharpUtils(Assembly fsharpCoreAssembly) private FSharpUtils(Assembly fsharpCoreAssembly)
{ {
FSharpCoreAssembly = fsharpCoreAssembly; FSharpCoreAssembly = fsharpCoreAssembly;
@@ -100,6 +103,8 @@ namespace Newtonsoft.Json.Utilities
} }
private MethodInfo _ofSeq; private MethodInfo _ofSeq;
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
private Type _mapType; private Type _mapType;
public Assembly FSharpCoreAssembly { get; private set; } public Assembly FSharpCoreAssembly { get; private set; }
@@ -117,6 +122,8 @@ namespace Newtonsoft.Json.Utilities
public const string FSharpListTypeName = "FSharpList`1"; public const string FSharpListTypeName = "FSharpList`1";
public const string FSharpMapTypeName = "FSharpMap`2"; public const string FSharpMapTypeName = "FSharpMap`2";
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static void EnsureInitialized(Assembly fsharpCoreAssembly) public static void EnsureInitialized(Assembly fsharpCoreAssembly)
{ {
if (_instance == null) if (_instance == null)
@@ -131,7 +138,11 @@ namespace Newtonsoft.Json.Utilities
} }
} }
private static MethodInfo GetMethodWithNonPublicFallback(Type type, string methodName, BindingFlags bindingFlags) private static MethodInfo GetMethodWithNonPublicFallback(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)]
Type type,
string methodName,
BindingFlags bindingFlags)
{ {
MethodInfo methodInfo = type.GetMethod(methodName, bindingFlags)!; MethodInfo methodInfo = type.GetMethod(methodName, bindingFlags)!;
@@ -147,6 +158,8 @@ namespace Newtonsoft.Json.Utilities
return methodInfo!; return methodInfo!;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
private static MethodCall<object?, object> CreateFSharpFuncCall(Type type, string methodName) private static MethodCall<object?, object> CreateFSharpFuncCall(Type type, string methodName)
{ {
MethodInfo innerMethodInfo = GetMethodWithNonPublicFallback(type, methodName, BindingFlags.Public | BindingFlags.Static); MethodInfo innerMethodInfo = GetMethodWithNonPublicFallback(type, methodName, BindingFlags.Public | BindingFlags.Static);
@@ -166,6 +179,8 @@ namespace Newtonsoft.Json.Utilities
return createFunction; return createFunction;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public ObjectConstructor<object> CreateSeq(Type t) public ObjectConstructor<object> CreateSeq(Type t)
{ {
MethodInfo seqType = _ofSeq.MakeGenericMethod(t); MethodInfo seqType = _ofSeq.MakeGenericMethod(t);
@@ -173,6 +188,8 @@ namespace Newtonsoft.Json.Utilities
return JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(seqType); return JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(seqType);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public ObjectConstructor<object> CreateMap(Type keyType, Type valueType) public ObjectConstructor<object> CreateMap(Type keyType, Type valueType)
{ {
MethodInfo creatorDefinition = typeof(FSharpUtils).GetMethod("BuildMapCreator")!; MethodInfo creatorDefinition = typeof(FSharpUtils).GetMethod("BuildMapCreator")!;
@@ -182,6 +199,8 @@ namespace Newtonsoft.Json.Utilities
return (ObjectConstructor<object>)creatorGeneric.Invoke(this, null)!; return (ObjectConstructor<object>)creatorGeneric.Invoke(this, null)!;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public ObjectConstructor<object> BuildMapCreator<TKey, TValue>() public ObjectConstructor<object> BuildMapCreator<TKey, TValue>()
{ {
Type genericMapType = _mapType.MakeGenericType(typeof(TKey), typeof(TValue)); Type genericMapType = _mapType.MakeGenericType(typeof(TKey), typeof(TValue));
@@ -0,0 +1,39 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#if !NET9_0_OR_GREATER
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>
/// Indicates that the specified public static boolean get-only property
/// guards access to the specified feature.
/// </summary>
/// <remarks>
/// Analyzers can use this to prevent warnings on calls to code that is
/// annotated as requiring that feature, when the callsite is guarded by a
/// call to the property.
/// </remarks>
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
internal sealed class FeatureGuardAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="FeatureGuardAttribute"/> class
/// with the specified feature type.
/// </summary>
/// <param name="featureType">
/// The type that represents the feature guarded by the property.
/// </param>
public FeatureGuardAttribute(Type featureType)
{
FeatureType = featureType;
}
/// <summary>
/// The type that represents the feature guarded by the property.
/// </summary>
public Type FeatureType { get; }
}
}
#endif // !NET9_0_OR_GREATER
@@ -0,0 +1,38 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#if !NET9_0_OR_GREATER
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>
/// Indicates that the specified public static boolean get-only property
/// corresponds to the feature switch specified by name.
/// </summary>
/// <remarks>
/// IL rewriters and compilers can use this to substitute the return value
/// of the specified property with the value of the feature switch.
/// </remarks>
[AttributeUsage(AttributeTargets.Property, Inherited = false)]
internal sealed class FeatureSwitchDefinitionAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="FeatureSwitchDefinitionAttribute"/> class
/// with the specified feature switch name.
/// </summary>
/// <param name="switchName">
/// The name of the feature switch that provides the value for the specified property.
/// </param>
public FeatureSwitchDefinitionAttribute(string switchName)
{
SwitchName = switchName;
}
/// <summary>
/// The name of the feature switch that provides the value for the specified property.
/// </summary>
public string SwitchName { get; }
}
}
#endif // !NET9_0_OR_GREATER
@@ -111,6 +111,8 @@ namespace Newtonsoft.Json.Utilities
new ImmutableCollectionTypeInfo(ImmutableDictionaryGenericTypeName, ImmutableDictionaryGenericTypeName, ImmutableDictionaryTypeName) new ImmutableCollectionTypeInfo(ImmutableDictionaryGenericTypeName, ImmutableDictionaryGenericTypeName, ImmutableDictionaryTypeName)
}; };
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
internal static bool TryBuildImmutableForArrayContract(Type underlyingType, Type collectionItemType, [NotNullWhen(true)]out Type? createdType, [NotNullWhen(true)]out ObjectConstructor<object>? parameterizedCreator) internal static bool TryBuildImmutableForArrayContract(Type underlyingType, Type collectionItemType, [NotNullWhen(true)]out Type? createdType, [NotNullWhen(true)]out ObjectConstructor<object>? parameterizedCreator)
{ {
if (underlyingType.IsGenericType()) if (underlyingType.IsGenericType())
@@ -143,6 +145,8 @@ namespace Newtonsoft.Json.Utilities
return false; return false;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
internal static bool TryBuildImmutableForDictionaryContract(Type underlyingType, Type keyItemType, Type valueItemType, [NotNullWhen(true)]out Type? createdType, [NotNullWhen(true)]out ObjectConstructor<object>? parameterizedCreator) internal static bool TryBuildImmutableForDictionaryContract(Type underlyingType, Type keyItemType, Type valueItemType, [NotNullWhen(true)]out Type? createdType, [NotNullWhen(true)]out ObjectConstructor<object>? parameterizedCreator)
{ {
if (underlyingType.IsGenericType()) if (underlyingType.IsGenericType())
@@ -26,6 +26,7 @@
using System; using System;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using System.Reflection; using System.Reflection;
using System.Diagnostics.CodeAnalysis;
#if !HAVE_LINQ #if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge; using Newtonsoft.Json.Utilities.LinqBridge;
@@ -39,6 +40,7 @@ namespace Newtonsoft.Json.Utilities
internal static ReflectionDelegateFactory Instance => _instance; internal static ReflectionDelegateFactory Instance => _instance;
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method) public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
{ {
ValidationUtils.ArgumentNotNull(method, nameof(method)); ValidationUtils.ArgumentNotNull(method, nameof(method));
@@ -53,6 +55,7 @@ namespace Newtonsoft.Json.Utilities
return a => method.Invoke(null, a)!; return a => method.Invoke(null, a)!;
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override MethodCall<T, object?> CreateMethodCall<T>(MethodBase method) public override MethodCall<T, object?> CreateMethodCall<T>(MethodBase method)
{ {
ValidationUtils.ArgumentNotNull(method, nameof(method)); ValidationUtils.ArgumentNotNull(method, nameof(method));
@@ -65,7 +68,10 @@ namespace Newtonsoft.Json.Utilities
return (o, a) => method.Invoke(o, a); return (o, a) => method.Invoke(o, a);
} }
public override Func<T> CreateDefaultConstructor<T>(Type type) [RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Func<T> CreateDefaultConstructor<T>(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
Type type)
{ {
ValidationUtils.ArgumentNotNull(type, nameof(type)); ValidationUtils.ArgumentNotNull(type, nameof(type));
@@ -83,6 +89,7 @@ namespace Newtonsoft.Json.Utilities
return () => (T)constructorInfo.Invoke(null); return () => (T)constructorInfo.Invoke(null);
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Func<T, object?> CreateGet<T>(PropertyInfo propertyInfo) public override Func<T, object?> CreateGet<T>(PropertyInfo propertyInfo)
{ {
ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo));
@@ -90,6 +97,7 @@ namespace Newtonsoft.Json.Utilities
return o => propertyInfo.GetValue(o, null); return o => propertyInfo.GetValue(o, null);
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Func<T, object?> CreateGet<T>(FieldInfo fieldInfo) public override Func<T, object?> CreateGet<T>(FieldInfo fieldInfo)
{ {
ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo));
@@ -97,6 +105,7 @@ namespace Newtonsoft.Json.Utilities
return o => fieldInfo.GetValue(o); return o => fieldInfo.GetValue(o);
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Action<T, object?> CreateSet<T>(FieldInfo fieldInfo) public override Action<T, object?> CreateSet<T>(FieldInfo fieldInfo)
{ {
ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo));
@@ -104,6 +113,7 @@ namespace Newtonsoft.Json.Utilities
return (o, v) => fieldInfo.SetValue(o, v); return (o, v) => fieldInfo.SetValue(o, v);
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public override Action<T, object?> CreateSet<T>(PropertyInfo propertyInfo) public override Action<T, object?> CreateSet<T>(PropertyInfo propertyInfo)
{ {
ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo));
@@ -40,6 +40,10 @@ namespace Newtonsoft.Json.Utilities
internal static class MiscellaneousUtils internal static class MiscellaneousUtils
{ {
internal const string TrimWarning = "Newtonsoft.Json relies on reflection over types that may be removed when trimming.";
internal const string AotWarning = "Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.";
[Conditional("DEBUG")] [Conditional("DEBUG")]
public static void Assert([DoesNotReturnIf(false)] bool condition, string? message = null) public static void Assert([DoesNotReturnIf(false)] bool condition, string? message = null)
{ {
@@ -24,6 +24,7 @@
#endregion #endregion
using System; using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using System.Reflection; using System.Reflection;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
@@ -36,6 +37,7 @@ namespace Newtonsoft.Json.Utilities
{ {
internal abstract class ReflectionDelegateFactory internal abstract class ReflectionDelegateFactory
{ {
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public Func<T, object?> CreateGet<T>(MemberInfo memberInfo) public Func<T, object?> CreateGet<T>(MemberInfo memberInfo)
{ {
if (memberInfo is PropertyInfo propertyInfo) if (memberInfo is PropertyInfo propertyInfo)
@@ -57,6 +59,7 @@ namespace Newtonsoft.Json.Utilities
throw new Exception("Could not create getter for {0}.".FormatWith(CultureInfo.InvariantCulture, memberInfo)); throw new Exception("Could not create getter for {0}.".FormatWith(CultureInfo.InvariantCulture, memberInfo));
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public Action<T, object?> CreateSet<T>(MemberInfo memberInfo) public Action<T, object?> CreateSet<T>(MemberInfo memberInfo)
{ {
if (memberInfo is PropertyInfo propertyInfo) if (memberInfo is PropertyInfo propertyInfo)
@@ -72,12 +75,21 @@ namespace Newtonsoft.Json.Utilities
throw new Exception("Could not create setter for {0}.".FormatWith(CultureInfo.InvariantCulture, memberInfo)); throw new Exception("Could not create setter for {0}.".FormatWith(CultureInfo.InvariantCulture, memberInfo));
} }
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public abstract MethodCall<T, object?> CreateMethodCall<T>(MethodBase method); public abstract MethodCall<T, object?> CreateMethodCall<T>(MethodBase method);
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public abstract ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method); public abstract ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method);
public abstract Func<T> CreateDefaultConstructor<T>(Type type); [RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public abstract Func<T> CreateDefaultConstructor<T>(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
Type type);
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public abstract Func<T, object?> CreateGet<T>(PropertyInfo propertyInfo); public abstract Func<T, object?> CreateGet<T>(PropertyInfo propertyInfo);
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public abstract Func<T, object?> CreateGet<T>(FieldInfo fieldInfo); public abstract Func<T, object?> CreateGet<T>(FieldInfo fieldInfo);
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public abstract Action<T, object?> CreateSet<T>(FieldInfo fieldInfo); public abstract Action<T, object?> CreateSet<T>(FieldInfo fieldInfo);
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public abstract Action<T, object?> CreateSet<T>(PropertyInfo propertyInfo); public abstract Action<T, object?> CreateSet<T>(PropertyInfo propertyInfo);
} }
} }
@@ -28,6 +28,8 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using System.Globalization; using System.Globalization;
using System.Diagnostics.CodeAnalysis;
#if !HAVE_LINQ #if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge; using Newtonsoft.Json.Utilities.LinqBridge;
#else #else
@@ -72,12 +74,35 @@ namespace Newtonsoft.Json.Utilities
return Members[member].MemberType!; return Members[member].MemberType!;
} }
public static ReflectionObject Create(Type t, params string[] memberNames) [RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static ReflectionObject Create(
[DynamicallyAccessedMembers(
DynamicallyAccessedMemberTypes.NonPublicConstructors |
DynamicallyAccessedMemberTypes.PublicConstructors |
DynamicallyAccessedMemberTypes.PublicEvents |
DynamicallyAccessedMemberTypes.PublicFields |
DynamicallyAccessedMemberTypes.PublicMethods |
DynamicallyAccessedMemberTypes.PublicNestedTypes |
DynamicallyAccessedMemberTypes.PublicProperties)]
Type t,
params string[] memberNames)
{ {
return Create(t, null, memberNames); return Create(t, null, memberNames);
} }
public static ReflectionObject Create(Type t, MethodBase? creator, params string[] memberNames) [RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public static ReflectionObject Create(
[DynamicallyAccessedMembers(
DynamicallyAccessedMemberTypes.NonPublicConstructors |
DynamicallyAccessedMemberTypes.PublicConstructors |
DynamicallyAccessedMemberTypes.PublicEvents |
DynamicallyAccessedMemberTypes.PublicFields |
DynamicallyAccessedMemberTypes.PublicMethods |
DynamicallyAccessedMemberTypes.PublicNestedTypes |
DynamicallyAccessedMemberTypes.PublicProperties)]
Type t,
MethodBase? creator,
params string[] memberNames)
{ {
ReflectionDelegateFactory delegateFactory = JsonTypeReflector.ReflectionDelegateFactory; ReflectionDelegateFactory delegateFactory = JsonTypeReflector.ReflectionDelegateFactory;
@@ -233,7 +233,9 @@ namespace Newtonsoft.Json.Utilities
return builder.ToString(); return builder.ToString();
} }
public static bool HasDefaultConstructor(Type t, bool nonPublic) public static bool HasDefaultConstructor(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type t,
bool nonPublic)
{ {
ValidationUtils.ArgumentNotNull(t, nameof(t)); ValidationUtils.ArgumentNotNull(t, nameof(t));
@@ -245,12 +247,15 @@ namespace Newtonsoft.Json.Utilities
return (GetDefaultConstructor(t, nonPublic) != null); return (GetDefaultConstructor(t, nonPublic) != null);
} }
public static ConstructorInfo? GetDefaultConstructor(Type t) public static ConstructorInfo? GetDefaultConstructor(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type t)
{ {
return GetDefaultConstructor(t, false); return GetDefaultConstructor(t, false);
} }
public static ConstructorInfo? GetDefaultConstructor(Type t, bool nonPublic) public static ConstructorInfo? GetDefaultConstructor(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type t,
bool nonPublic)
{ {
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
if (nonPublic) if (nonPublic)
@@ -305,12 +310,18 @@ namespace Newtonsoft.Json.Utilities
return (t == genericInterfaceDefinition); return (t == genericInterfaceDefinition);
} }
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition) public static bool ImplementsGenericDefinition(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)]
Type type,
Type genericInterfaceDefinition)
{ {
return ImplementsGenericDefinition(type, genericInterfaceDefinition, out _); return ImplementsGenericDefinition(type, genericInterfaceDefinition, out _);
} }
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, [NotNullWhen(true)]out Type? implementingType) public static bool ImplementsGenericDefinition(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] Type type,
Type genericInterfaceDefinition,
[NotNullWhen(true)]out Type? implementingType)
{ {
ValidationUtils.ArgumentNotNull(type, nameof(type)); ValidationUtils.ArgumentNotNull(type, nameof(type));
ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, nameof(genericInterfaceDefinition)); ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, nameof(genericInterfaceDefinition));
@@ -394,7 +405,9 @@ namespace Newtonsoft.Json.Utilities
/// </summary> /// </summary>
/// <param name="type">The type.</param> /// <param name="type">The type.</param>
/// <returns>The type of the typed collection's items.</returns> /// <returns>The type of the typed collection's items.</returns>
public static Type? GetCollectionItemType(Type type) public static Type? GetCollectionItemType(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)]
Type type)
{ {
ValidationUtils.ArgumentNotNull(type, nameof(type)); ValidationUtils.ArgumentNotNull(type, nameof(type));
@@ -419,7 +432,11 @@ namespace Newtonsoft.Json.Utilities
throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type));
} }
public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type? keyType, out Type? valueType) public static void GetDictionaryKeyValueTypes(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)]
Type dictionaryType,
out Type? keyType,
out Type? valueType)
{ {
ValidationUtils.ArgumentNotNull(dictionaryType, nameof(dictionaryType)); ValidationUtils.ArgumentNotNull(dictionaryType, nameof(dictionaryType));
@@ -648,6 +665,7 @@ namespace Newtonsoft.Json.Utilities
} }
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr) public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr)
{ {
List<MemberInfo> targetMembers = new List<MemberInfo>(); List<MemberInfo> targetMembers = new List<MemberInfo>();
@@ -701,6 +719,7 @@ namespace Newtonsoft.Json.Utilities
return distinctMembers; return distinctMembers;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr) private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr)
{ {
if (memberInfo.MemberType() != MemberTypes.Property) if (memberInfo.MemberType() != MemberTypes.Property)
@@ -885,7 +904,22 @@ namespace Newtonsoft.Json.Utilities
return null; return null;
} }
public static MemberInfo? GetMemberInfoFromType(Type targetType, MemberInfo memberInfo) public static MemberInfo? GetMemberInfoFromType(
[DynamicallyAccessedMembers(
DynamicallyAccessedMemberTypes.NonPublicConstructors |
DynamicallyAccessedMemberTypes.NonPublicEvents |
DynamicallyAccessedMemberTypes.NonPublicFields |
DynamicallyAccessedMemberTypes.NonPublicMethods |
DynamicallyAccessedMemberTypes.NonPublicNestedTypes |
DynamicallyAccessedMemberTypes.NonPublicProperties |
DynamicallyAccessedMemberTypes.PublicConstructors |
DynamicallyAccessedMemberTypes.PublicEvents |
DynamicallyAccessedMemberTypes.PublicFields |
DynamicallyAccessedMemberTypes.PublicMethods |
DynamicallyAccessedMemberTypes.PublicNestedTypes |
DynamicallyAccessedMemberTypes.PublicProperties)]
Type targetType,
MemberInfo memberInfo)
{ {
const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
@@ -902,7 +936,11 @@ namespace Newtonsoft.Json.Utilities
} }
} }
public static IEnumerable<FieldInfo> GetFields(Type targetType, BindingFlags bindingAttr) [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
public static IEnumerable<FieldInfo> GetFields(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)]
Type targetType,
BindingFlags bindingAttr)
{ {
ValidationUtils.ArgumentNotNull(targetType, nameof(targetType)); ValidationUtils.ArgumentNotNull(targetType, nameof(targetType));
@@ -917,6 +955,7 @@ namespace Newtonsoft.Json.Utilities
} }
#if !PORTABLE #if !PORTABLE
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
private static void GetChildPrivateFields(IList<MemberInfo> initialFields, Type type, BindingFlags bindingAttr) private static void GetChildPrivateFields(IList<MemberInfo> initialFields, Type type, BindingFlags bindingAttr)
{ {
Type? targetType = type; Type? targetType = type;
@@ -940,6 +979,7 @@ namespace Newtonsoft.Json.Utilities
} }
#endif #endif
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr) public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr)
{ {
ValidationUtils.ArgumentNotNull(targetType, nameof(targetType)); ValidationUtils.ArgumentNotNull(targetType, nameof(targetType));
@@ -978,6 +1018,7 @@ namespace Newtonsoft.Json.Utilities
: bindingAttr; : bindingAttr;
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
private static void GetChildPrivateProperties(IList<PropertyInfo> initialProperties, Type type, BindingFlags bindingAttr) private static void GetChildPrivateProperties(IList<PropertyInfo> initialProperties, Type type, BindingFlags bindingAttr)
{ {
// fix weirdness with private PropertyInfos only being returned for the current Type // fix weirdness with private PropertyInfos only being returned for the current Type
@@ -1045,7 +1086,11 @@ namespace Newtonsoft.Json.Utilities
} }
} }
public static bool IsMethodOverridden(Type currentType, Type methodDeclaringType, string method) public static bool IsMethodOverridden(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)]
Type currentType,
Type methodDeclaringType,
string method)
{ {
bool isMethodOverriden = currentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) bool isMethodOverriden = currentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Any(info => .Any(info =>
@@ -1058,7 +1103,9 @@ namespace Newtonsoft.Json.Utilities
return isMethodOverriden; return isMethodOverriden;
} }
public static object? GetDefaultValue(Type type) public static object? GetDefaultValue(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
Type type)
{ {
if (!type.IsValueType()) if (!type.IsValueType())
{ {
@@ -0,0 +1,43 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#if !NET7_0_OR_GREATER
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>
/// Indicates that the specified method requires the ability to generate new code at runtime,
/// for example through <see cref="Reflection"/>.
/// </summary>
/// <remarks>
/// This allows tools to understand which methods are unsafe to call when compiling ahead of time.
/// </remarks>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)]
internal sealed class RequiresDynamicCodeAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="RequiresDynamicCodeAttribute"/> class
/// with the specified message.
/// </summary>
/// <param name="message">
/// A message that contains information about the usage of dynamic code.
/// </param>
public RequiresDynamicCodeAttribute(string message)
{
Message = message;
}
/// <summary>
/// Gets a message that contains information about the usage of dynamic code.
/// </summary>
public string Message { get; }
/// <summary>
/// Gets or sets an optional URL that contains more information about the method,
/// why it requires dynamic code, and what options a consumer has to deal with it.
/// </summary>
public string? Url { get; set; }
}
}
#endif // !NET7_0_OR_GREATER
@@ -0,0 +1,44 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#if !NET5_0_OR_GREATER
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>
/// Indicates that the specified method requires dynamic access to code that is not referenced
/// statically, for example through <see cref="Reflection"/>.
/// </summary>
/// <remarks>
/// This allows tools to understand which methods are unsafe to call when removing unreferenced
/// code from an application.
/// </remarks>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)]
internal sealed class RequiresUnreferencedCodeAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="RequiresUnreferencedCodeAttribute"/> class
/// with the specified message.
/// </summary>
/// <param name="message">
/// A message that contains information about the usage of unreferenced code.
/// </param>
public RequiresUnreferencedCodeAttribute(string message)
{
Message = message;
}
/// <summary>
/// Gets a message that contains information about the usage of unreferenced code.
/// </summary>
public string Message { get; }
/// <summary>
/// Gets or sets an optional URL that contains more information about the method,
/// why it requires unreferenced code, and what options a consumer has to deal with it.
/// </summary>
public string? Url { get; set; }
}
}
#endif // !NET5_0_OR_GREATER
+28 -15
View File
@@ -578,7 +578,31 @@ namespace Newtonsoft.Json.Utilities
#endif #endif
} }
public static bool AssignableToTypeName(this Type type, string fullTypeName, bool searchInterfaces, [NotNullWhen(true)]out Type? match) public static bool AssignableToTypeNameIncludingInterfaces(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)]
this Type type,
string fullTypeName,
[NotNullWhen(true)]out Type? match)
{
if (AssignableToTypeName(type, fullTypeName, out match))
{
return true;
}
foreach (Type i in type.GetInterfaces())
{
if (string.Equals(i.Name, fullTypeName, StringComparison.Ordinal))
{
match = type;
return true;
}
}
match = null;
return false;
}
public static bool AssignableToTypeName(this Type type, string fullTypeName, [NotNullWhen(true)]out Type? match)
{ {
Type? current = type; Type? current = type;
@@ -593,27 +617,16 @@ namespace Newtonsoft.Json.Utilities
current = current.BaseType(); current = current.BaseType();
} }
if (searchInterfaces)
{
foreach (Type i in type.GetInterfaces())
{
if (string.Equals(i.Name, fullTypeName, StringComparison.Ordinal))
{
match = type;
return true;
}
}
}
match = null; match = null;
return false; return false;
} }
public static bool AssignableToTypeName(this Type type, string fullTypeName, bool searchInterfaces) public static bool AssignableToTypeName(this Type type, string fullTypeName)
{ {
return type.AssignableToTypeName(fullTypeName, searchInterfaces, out _); return AssignableToTypeName(type, fullTypeName, out _);
} }
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
public static bool ImplementInterface(this Type type, Type interfaceType) public static bool ImplementInterface(this Type type, Type interfaceType)
{ {
for (Type? currentType = type; currentType != null; currentType = currentType.BaseType()) for (Type? currentType = type; currentType != null; currentType = currentType.BaseType())
@@ -0,0 +1,89 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#if !NET5_0_OR_GREATER
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>
/// Suppresses reporting of a specific rule violation, allowing multiple suppressions on a
/// single code artifact.
/// </summary>
/// <remarks>
/// <see cref="UnconditionalSuppressMessageAttribute"/> is different than
/// <see cref="SuppressMessageAttribute"/> in that it doesn't have a
/// <see cref="ConditionalAttribute"/>. So it is always preserved in the compiled assembly.
/// </remarks>
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
internal sealed class UnconditionalSuppressMessageAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="UnconditionalSuppressMessageAttribute"/>
/// class, specifying the category of the tool and the identifier for an analysis rule.
/// </summary>
/// <param name="category">The category for the attribute.</param>
/// <param name="checkId">The identifier of the analysis rule the attribute applies to.</param>
public UnconditionalSuppressMessageAttribute(string category, string checkId)
{
Category = category;
CheckId = checkId;
}
/// <summary>
/// Gets the category identifying the classification of the attribute.
/// </summary>
/// <remarks>
/// The <see cref="Category"/> property describes the tool or tool analysis category
/// for which a message suppression attribute applies.
/// </remarks>
public string Category { get; }
/// <summary>
/// Gets the identifier of the analysis tool rule to be suppressed.
/// </summary>
/// <remarks>
/// Concatenated together, the <see cref="Category"/> and <see cref="CheckId"/>
/// properties form a unique check identifier.
/// </remarks>
public string CheckId { get; }
/// <summary>
/// Gets or sets the scope of the code that is relevant for the attribute.
/// </summary>
/// <remarks>
/// The Scope property is an optional argument that specifies the metadata scope for which
/// the attribute is relevant.
/// </remarks>
public string? Scope { get; set; }
/// <summary>
/// Gets or sets a fully qualified path that represents the target of the attribute.
/// </summary>
/// <remarks>
/// The <see cref="Target"/> property is an optional argument identifying the analysis target
/// of the attribute. An example value is "System.IO.Stream.ctor():System.Void".
/// Because it is fully qualified, it can be long, particularly for targets such as parameters.
/// The analysis tool user interface should be capable of automatically formatting the parameter.
/// </remarks>
public string? Target { get; set; }
/// <summary>
/// Gets or sets an optional argument expanding on exclusion criteria.
/// </summary>
/// <remarks>
/// The <see cref="MessageId "/> property is an optional argument that specifies additional
/// exclusion where the literal metadata target is not sufficiently precise. For example,
/// the <see cref="UnconditionalSuppressMessageAttribute"/> cannot be applied within a method,
/// and it may be desirable to suppress a violation against a statement in the method that will
/// give a rule violation, but not against all statements in the method.
/// </remarks>
public string? MessageId { get; set; }
/// <summary>
/// Gets or sets the justification for suppressing the code analysis message.
/// </summary>
public string? Justification { get; set; }
}
}
#endif // !NET5_0_OR_GREATER