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