下面是序列化 ChatResponseMessage 的代码
var message = AzureOpenAIModelFactory.ChatResponseMessage(ChatRole.Assistant, "OK");
var json = JsonSerializer.Serialize(
message,
new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
});
Console.WriteLine(json);
输出的 json 却丢了 role
属性(类型是 ChatRole
)的值
{
"role": {},
"content": "OK",
"toolCalls": [],
"functionCall": null,
"azureExtensionsContext": null
}
请问如何解决这个问题?
在 github 的这个 issue How to deserialize OpenAI ChatMessage correctly? 的评论中知道了原因:
the issue is that the generated ChatRole type has a private, non-property field that doesn't work nicely by default with System.Text.Json.Serialization. I suspect deeper inspection will reveal that Role on a ChatMessage gets serialized with an empty value, which definitely makes deserialization incorrect later on.