feature: Add Parse & TryParse to EmbedBuilder & Add ToJsonString extension (#2284)

* Add parse & tryparse to embedbuilder.

* Add tostring extension for embeds

* Modify comments

* Resolve suggestions

* Update src/Discord.Net.Rest/Extensions/StringExtensions.cs

Co-authored-by: Quin Lynch <49576606+quinchs@users.noreply.github.com>
This commit is contained in:
Armano den Boef
2022-05-18 09:57:37 +02:00
committed by GitHub
parent a24dde4b19
commit cea59b55ba
2 changed files with 97 additions and 0 deletions

View File

@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Discord.Utils;
using Newtonsoft.Json;
namespace Discord
{
@@ -155,6 +156,55 @@ namespace Discord
}
}
/// <summary>
/// Tries to parse a string into an <see cref="EmbedBuilder"/>.
/// </summary>
/// <param name="json">The json string to parse.</param>
/// <param name="builder">The <see cref="EmbedBuilder"/> with populated values. An empty instance if method returns <see langword="false"/>.</param>
/// <returns><see langword="true"/> if <paramref name="json"/> was succesfully parsed. <see langword="false"/> if not.</returns>
public static bool TryParse(string json, out EmbedBuilder builder)
{
builder = new EmbedBuilder();
try
{
var model = JsonConvert.DeserializeObject<Embed>(json);
if (model is not null)
{
builder = model.ToEmbedBuilder();
return true;
}
return false;
}
catch
{
return false;
}
}
/// <summary>
/// Parses a string into an <see cref="EmbedBuilder"/>.
/// </summary>
/// <param name="json">The json string to parse.</param>
/// <returns>An <see cref="EmbedBuilder"/> with populated values from the passed <paramref name="json"/>.</returns>
/// <exception cref="InvalidOperationException">Thrown if the string passed is not valid json.</exception>
public static EmbedBuilder Parse(string json)
{
try
{
var model = JsonConvert.DeserializeObject<Embed>(json);
if (model is not null)
return model.ToEmbedBuilder();
return new EmbedBuilder();
}
catch
{
throw;
}
}
/// <summary>
/// Sets the title of an <see cref="Embed"/>.
/// </summary>