fix: when serializing source use media type to deserialize to image or document source
This commit is contained in:
@@ -16,11 +16,20 @@ class SourceConverter : JsonConverter<Source>
|
|||||||
{
|
{
|
||||||
SourceType.Text => JsonSerializer.Deserialize<TextSource>(root.GetRawText(), options)!,
|
SourceType.Text => JsonSerializer.Deserialize<TextSource>(root.GetRawText(), options)!,
|
||||||
SourceType.Content => JsonSerializer.Deserialize<CustomSource>(root.GetRawText(), options)!,
|
SourceType.Content => JsonSerializer.Deserialize<CustomSource>(root.GetRawText(), options)!,
|
||||||
SourceType.Base64 => JsonSerializer.Deserialize<Base64Source>(root.GetRawText(), options)!,
|
SourceType.Base64 => DeserializeBase64Source(root, options),
|
||||||
_ => throw new JsonException($"Unknown content type: {type}")
|
_ => throw new JsonException($"Unknown content type: {type}")
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static Source DeserializeBase64Source(JsonElement root, JsonSerializerOptions options)
|
||||||
|
{
|
||||||
|
var mediaType = root.GetProperty("media_type").GetString() ?? throw new JsonException("Missing 'media_type' property");
|
||||||
|
var isImage = ImageType.IsValidImageType(mediaType);
|
||||||
|
return isImage
|
||||||
|
? JsonSerializer.Deserialize<ImageSource>(root.GetRawText(), options)!
|
||||||
|
: JsonSerializer.Deserialize<DocumentSource>(root.GetRawText(), options)!;
|
||||||
|
}
|
||||||
|
|
||||||
public override void Write(Utf8JsonWriter writer, Source value, JsonSerializerOptions options)
|
public override void Write(Utf8JsonWriter writer, Source value, JsonSerializerOptions options)
|
||||||
{
|
{
|
||||||
if (value is TextSource textSource)
|
if (value is TextSource textSource)
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ public class MessageRequestTests : SerializationTest
|
|||||||
""content"": [
|
""content"": [
|
||||||
{
|
{
|
||||||
""type"": ""image"",
|
""type"": ""image"",
|
||||||
""source"": { ""media_type"": ""image/jpeg"", ""data"": ""data"" }
|
""source"": { ""type"": ""base64"", ""media_type"": ""image/jpeg"", ""data"": ""data"" }
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user