2024-06-27 23:26:53 -05:00
|
|
|
using System.Text.Json;
|
|
|
|
|
using System.Text.Json.Serialization;
|
|
|
|
|
|
|
|
|
|
using AnthropicClient.Models;
|
|
|
|
|
|
|
|
|
|
namespace AnthropicClient.Json;
|
|
|
|
|
|
|
|
|
|
class ContentConverter : JsonConverter<Content>
|
|
|
|
|
{
|
|
|
|
|
public override Content Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
|
|
|
|
{
|
|
|
|
|
using var jsonDocument = JsonDocument.ParseValue(ref reader);
|
|
|
|
|
var root = jsonDocument.RootElement;
|
|
|
|
|
var type = root.GetProperty("type").GetString();
|
|
|
|
|
return type switch
|
|
|
|
|
{
|
|
|
|
|
ContentType.Text => JsonSerializer.Deserialize<TextContent>(root.GetRawText(), options)!,
|
|
|
|
|
ContentType.Image => JsonSerializer.Deserialize<ImageContent>(root.GetRawText(), options)!,
|
2024-11-21 13:43:21 -06:00
|
|
|
ContentType.Document => JsonSerializer.Deserialize<DocumentContent>(root.GetRawText(), options)!,
|
2024-06-27 23:26:53 -05:00
|
|
|
ContentType.ToolUse => JsonSerializer.Deserialize<ToolUseContent>(root.GetRawText(), options)!,
|
|
|
|
|
ContentType.ToolResult => JsonSerializer.Deserialize<ToolResultContent>(root.GetRawText(), options)!,
|
|
|
|
|
_ => throw new JsonException($"Unknown content type: {type}")
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override void Write(Utf8JsonWriter writer, Content value, JsonSerializerOptions options)
|
|
|
|
|
{
|
|
|
|
|
JsonSerializer.Serialize(writer, value, value.GetType(), options);
|
|
|
|
|
}
|
|
|
|
|
}
|