Browse Source

Add NodeConnectionBase Json converter

pull/495/head
Ionite 9 months ago
parent
commit
d12e04a69b
No known key found for this signature in database
  1. 49
      StabilityMatrix.Core/Converters/Json/NodeConnectionBaseJsonConverter.cs
  2. 6
      StabilityMatrix.Core/Inference/ComfyClient.cs
  3. 6
      StabilityMatrix.Core/Models/Api/Comfy/NodeTypes/NodeConnectionBase.cs

49
StabilityMatrix.Core/Converters/Json/NodeConnectionBaseJsonConverter.cs

@ -0,0 +1,49 @@
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using StabilityMatrix.Core.Models.Api.Comfy.NodeTypes;
namespace StabilityMatrix.Core.Converters.Json;
public class NodeConnectionBaseJsonConverter : JsonConverter<NodeConnectionBase>
{
/// <inheritdoc />
public override NodeConnectionBase Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options
)
{
// Read as Data array
reader.Read();
var data = new object[2];
reader.Read();
data[0] = reader.GetString() ?? throw new JsonException("Expected string for node name");
reader.Read();
data[1] = reader.GetInt32();
reader.Read();
if (Activator.CreateInstance(typeToConvert) is not NodeConnectionBase instance)
{
throw new JsonException($"Failed to create instance of {typeToConvert}");
}
var propertyInfo =
typeToConvert.GetProperty("Data", BindingFlags.Public | BindingFlags.Instance)
?? throw new JsonException($"Failed to get Data property of {typeToConvert}");
propertyInfo.SetValue(instance, data);
return instance;
}
/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, NodeConnectionBase value, JsonSerializerOptions options)
{
// Write as Data array
writer.WriteStartArray();
writer.WriteStringValue(value.Data?[0] as string);
writer.WriteNumberValue((int)value.Data?[1]!);
writer.WriteEndArray();
}
}

6
StabilityMatrix.Core/Inference/ComfyClient.cs

@ -33,7 +33,11 @@ public class ComfyClient : InferenceClientBase
new() new()
{ {
PropertyNamingPolicy = JsonNamingPolicies.SnakeCaseLower, PropertyNamingPolicy = JsonNamingPolicies.SnakeCaseLower,
Converters = { new OneOfJsonConverter<string, StringNodeConnection>() } Converters =
{
new NodeConnectionBaseJsonConverter(),
new OneOfJsonConverter<string, StringNodeConnection>()
}
}; };
// ReSharper disable once MemberCanBePrivate.Global // ReSharper disable once MemberCanBePrivate.Global

6
StabilityMatrix.Core/Models/Api/Comfy/NodeTypes/NodeConnectionBase.cs

@ -1,5 +1,9 @@
namespace StabilityMatrix.Core.Models.Api.Comfy.NodeTypes; using System.Text.Json.Serialization;
using StabilityMatrix.Core.Converters.Json;
namespace StabilityMatrix.Core.Models.Api.Comfy.NodeTypes;
[JsonConverter(typeof(NodeConnectionBaseJsonConverter))]
public abstract class NodeConnectionBase public abstract class NodeConnectionBase
{ {
/// <summary> /// <summary>

Loading…
Cancel
Save