78 lines
2.2 KiB
C#
78 lines
2.2 KiB
C#
using System;
|
|
|
|
using MfGames.Gallium;
|
|
using MfGames.Nitride.Contents;
|
|
|
|
using Newtonsoft.Json;
|
|
|
|
namespace MfGames.Nitride.Json;
|
|
|
|
public static class NitrideJsonEntityExtensions
|
|
{
|
|
/// <summary>
|
|
/// Parses the entity text as a JSON file and returns the results.
|
|
/// </summary>
|
|
public static TType? GetTextContentJson<TType>(
|
|
this Entity entity,
|
|
Action<JsonSerializerSettings> configure)
|
|
{
|
|
JsonSerializerSettings settings = new();
|
|
|
|
configure.Invoke(settings);
|
|
|
|
return entity.GetTextContentJson<TType>(settings);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Parses the entity text as a JSON file and returns the results.
|
|
/// </summary>
|
|
public static TType? GetTextContentJson<TType>(
|
|
this Entity entity,
|
|
JsonSerializerSettings? settings = null)
|
|
{
|
|
string? text = entity.GetTextContentString();
|
|
|
|
return text != null
|
|
? JsonConvert.DeserializeObject<TType>(text, settings)
|
|
: default;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sets the text content to the serialized value. If this is null, then
|
|
/// the text content is removed. This uses the default serializer which
|
|
/// may be configured.
|
|
/// </summary>
|
|
/// <returns>The same entity for chaining methods.</returns>
|
|
public static Entity SetTextContentJson<TType>(
|
|
this Entity entity,
|
|
TType? value,
|
|
Action<JsonSerializerSettings> configure)
|
|
{
|
|
JsonSerializerSettings settings = new();
|
|
|
|
configure.Invoke(settings);
|
|
|
|
return SetTextContentJson(entity, value, settings);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sets the text content to the serialized value using the serializer
|
|
/// provided. If the value is null, then the text content is removed.
|
|
/// </summary>
|
|
/// <returns>The same entity for chaining methods.</returns>
|
|
public static Entity SetTextContentJson<TType>(
|
|
this Entity entity,
|
|
TType? value,
|
|
JsonSerializerSettings? settings = null)
|
|
{
|
|
if (value == null)
|
|
{
|
|
return entity.Remove<ITextContent>();
|
|
}
|
|
|
|
string json = JsonConvert.SerializeObject(value, settings);
|
|
|
|
return entity.SetTextContent(json);
|
|
}
|
|
}
|