1
0

Erweiterung der UnitTests und kleinere Fixes

This commit is contained in:
2021-11-17 23:30:54 +01:00
parent 3a0732dd22
commit 80fc6ff2b3
16 changed files with 873 additions and 37 deletions

View File

@@ -1,5 +1,4 @@
using System;
using System.Collections;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
@@ -36,6 +35,34 @@ namespace Newtonsoft.Json
JsonConvert.PopulateObject(json, target, jsonSerializerSettings);
}
/// <summary>
/// Deserializes a JSON string into a new instance.
/// </summary>
/// <typeparam name="T">The type of the instance to deserialize.</typeparam>
/// <param name="json">The JSON string to read the values from.</param>
/// <returns>A new instance of <typeparamref name="T"/> with the deserialized values.</returns>
public static T DeserializeJson<T>(this string json)
=> JsonConvert.DeserializeObject<T>(json, jsonSerializerSettings);
/// <summary>
/// Deserializes a JSON string into a new instance or using the fallback value.
/// </summary>
/// <typeparam name="T">The type of the instance to deserialize.</typeparam>
/// <param name="json">The JSON string to read the values from.</param>
/// <param name="fallbackValue">A fallback value when deserialization fails.</param>
/// <returns>A new instance of <typeparamref name="T"/> with the deserialized values or the fallback value.</returns>
public static T DeserializeJson<T>(this string json, T fallbackValue)
{
try
{
return JsonConvert.DeserializeObject<T>(json, jsonSerializerSettings);
}
catch
{
return fallbackValue;
}
}
/// <summary>
/// Serializes an instance to a JSON string.
/// </summary>
@@ -63,29 +90,13 @@ namespace Newtonsoft.Json
a.ErrorContext.Handled = true;
};
if (includeType)
serializer.TypeNameHandling = TypeNameHandling.Auto;
serializer.TypeNameHandling = includeType ? TypeNameHandling.All : TypeNameHandling.None;
serializer.Serialize(jw, source, typeof(T));
}
return sb.ToString().Trim();
}
/// <summary>
/// Deserializes a JSON string into a new instance.
/// </summary>
/// <typeparam name="T">The type of the instance to deserialize.</typeparam>
/// <param name="json">The JSON string to read the values from.</param>
/// <param name="fallback">A fallback value.</param>
/// <returns>A new instance of <typeparamref name="T"/> with the deserialized values.</returns>
public static T DeserializeJson<T>(this string json, T fallback = default)
{
if (!string.IsNullOrWhiteSpace(json))
return JsonConvert.DeserializeObject<T>(json, jsonSerializerSettings);
return fallback;
}
/// <summary>
/// Converts an object into a JObject using the custom serializer settings.
/// </summary>
@@ -141,10 +152,7 @@ namespace Newtonsoft.Json
if (lvlObj == null)
return defaultValue;
if (typeof(T) == typeof(string))
return (T)Convert.ChangeType(lvlObj, typeof(T));
return DeepConvert.ChangeType<T>(lvlObj);
return DeepConvert.ChangeType<T>(lvlObj is JValue ? ((JValue)lvlObj).Value : lvlObj.Value<object>());
}
/// <summary>