BotFramework 和 LUIS 的 JSON 序列化程序错误



StackOverflow Community!

我有一个聊天机器人,并集成了 LUIS.ai,使其更智能。其中一个对话即将与主管(老师)预约 一切都运行良好,代码完全相同。几个小时前,我遇到了一些奇怪的错误。

Exception: Type 'Newtonsoft.Json.Linq.JArray' in Assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' is not marked as serializable.

如何重现错误?

如果用户的输入中缺少两个实体(教师和日期),则它可以正常工作,机器人会生成表单,请求缺少输入并显示建议的会议时间。

如果输入中缺少其中一个实体,它将构建一个表单并询问缺少的日期或教师实体,并显示建议的会议时间。

如果用户的输入同时包含实体:教师和日期,那么我会收到错误。

这是我的 WebApiConfig 类:

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Json settings
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Newtonsoft.Json.Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
};
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}

我仅在尝试从用户话语中获取实体(一种内置的.dateTimeV2)时遇到此错误。

此异步方法称为:

//From the LUIS.AI language model the entities
private const string EntityMeetingDate = "MeetingDate";
private const string EntityTeacher = "Teacher";
[LuisIntent("BookSupervision")]
public async Task BookAppointment(IDialogContext context, IAwaitable<IMessageActivity> activity, LuisResult result)
{
var message = await activity;
await context.PostAsync($"I am analysing your message: '{message.Text}'...");
var meetingsQuery = new MeetingsQuery();
EntityRecommendation teacherEntityRecommendation;
EntityRecommendation dateEntityRecommendation;
if (result.TryFindEntity(EntityTeacher, out teacherEntityRecommendation))
{
teacherEntityRecommendation.Type = "Name";
}
if (result.TryFindEntity(EntityMeetingDate, out dateEntityRecommendation))
{
dateEntityRecommendation.Type = "Date";
}
var meetingsFormDialog = new FormDialog<MeetingsQuery>(meetingsQuery, this.BuildMeetingsForm, FormOptions.PromptInStart, result.Entities);
context.Call(meetingsFormDialog, this.ResumeAfterMeetingsFormDialog);
}

构建表单的更多方法:

private IForm<MeetingsQuery> BuildMeetingsForm()
{
OnCompletionAsyncDelegate<MeetingsQuery> processMeetingsSearch = async (context, state) =>
{
var message = "Searching for supervision slots";
if (!string.IsNullOrEmpty(state.Date))
{
message += $" at {state.Date}...";
}
else if (!string.IsNullOrEmpty(state.Name))
{
message += $" with professor {state.Name}...";
}
await context.PostAsync(message);
};
return new FormBuilder<MeetingsQuery>()
.Field(nameof(MeetingsQuery.Date), (state) => string.IsNullOrEmpty(state.Date))
.Field(nameof(MeetingsQuery.Name), (state) => string.IsNullOrEmpty(state.Name))
.OnCompletion(processMeetingsSearch)
.Build();
}
private async Task ResumeAfterMeetingsFormDialog(IDialogContext context, IAwaitable<MeetingsQuery> result)
{
try
{
var searchQuery = await result;
var meetings = await this.GetMeetingsAsync(searchQuery);
await context.PostAsync($"I found {meetings.Count()} available slots:");
var resultMessage = context.MakeMessage();
resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
resultMessage.Attachments = new List<Attachment>();
foreach (var meeting in meetings)
{
HeroCard heroCard = new HeroCard()
{
Title = meeting.Teacher,
Subtitle = meeting.Location,
Text = meeting.DateTime,
Images = new List<CardImage>()
{
new CardImage() {Url = meeting.Image}
},
Buttons = new List<CardAction>()
{
new CardAction()
{
Title = "Book Appointment",
Type = ActionTypes.OpenUrl,
Value = $"https://www.bing.com/search?q=easj+roskilde+" + HttpUtility.UrlEncode(meeting.Location)
}
}
};
resultMessage.Attachments.Add(heroCard.ToAttachment());
}
await context.PostAsync(resultMessage);
}
catch (FormCanceledException ex)
{
string reply;
if (ex.InnerException == null)
{
reply = "You have canceled the operation.";
}
else
{
reply = $"Oops! Something went wrong :( Technical Details: {ex.InnerException.Message}";
}
await context.PostAsync(reply);
}
finally
{
context.Wait(DeconstructionOfDialog);
}
}

private async Task<IEnumerable<Meeting>> GetMeetingsAsync(MeetingsQuery searchQuery)
{
var meetings = new List<Meeting>();
//some random result manually for demo purposes
for (int i = 1; i <= 5; i++)
{
var random = new Random(i);
Meeting meeting = new Meeting()
{
DateTime = $" Available time: {searchQuery.Date} At building {i}",
Teacher = $" Professor {searchQuery.Name}",
Location = $" Elisagårdsvej 3, Room {random.Next(1, 300)}",
Image = $"https://placeholdit.imgix.net/~text?txtsize=35&txt=Supervision+{i}&w=500&h=260"
};
meetings.Add(meeting);
}
return meetings;
}

最奇怪的是,这段代码奏效了,我对 GitHub 上的社区大喊大叫和尊重,因为我认为这是一个很棒的平台,拥有大量的文档和示例。

这是已知问题(也在此处和此处报告)。

长话短说,由于 BotBuilder 尚不支持内置的 .datetimeV2.* 实体,因此EntityRecommendationResolution字典最终会以一个值为JArray的条目结束。当您将这些实体传递给FormDialog时,就会出现问题。由于实体是对话框中的私有字段,当然,与任何其他对话框一样,正在序列化,因此会引发异常,因为Newtonsoft中的JArray类未标记为可序列化。

此处提供了添加对 datetimeV2 实体的支持的请求。

我现在能想到的解决方法是手动提取 DateTime 实体的值,并将其分配给要传递给FormDialogMeetingsQuery实例的Date字段,并从要传递给FormDialogresult.Entities集合中删除 DateTime 实体。

更新

这已在 SDK 中修复,如您在此拉取请求中看到的那样。

相关内容

最新更新