简体   繁体   English

如何在自适应对话框 HttpRequest 中从 xml 转换为 json?

[英]How to convert from xml to json within Adaptive dialog HttpRequest?

I am new to Bot Framework and C#.我是 Bot Framework 和 C# 的新手。 I am building a chatbot using Adaptive Dialog with the Core Flight Booking Template ( adaptive-dialog/03.core-bot ).我正在使用带有核心航班预订模板 ( adaptive-dialog/03.core-bot ) 的自适应对话框构建聊天机器人。 I want to make an API call to get the weather information.我想拨打 API 电话以获取天气信息。 This OpenWeather API can return data in JSON, XML, or HTML format.此 OpenWeather API 可以返回 JSON、XML 或 Z4C4AD5FCA2E7A3F74DBB1AACED0 格式的数据。 When the response is in JSON format, it is easy to access the key-value pairs.当响应为 JSON 格式时,很容易访问键值对。 But when the response is in XML format, everything will be converted into a string and saved as 'content' in the response, I have to convert it into either JSON or a Dictionary so that I can access the detailed information.但是当响应为 XML 格式时,所有内容都将转换为字符串并保存为响应中的“内容”,我必须将其转换为 JSON 或字典,以便我可以访问详细信息。 And I need to save the API response as a property in the dialog for later reference.我需要将 API 响应保存为对话框中的属性,以供以后参考。

I know we can use the following code to convert from XML to JSON, but the question is how to do it in the adaptive dialog.我知道我们可以使用以下代码将 XML 转换为 JSON,但问题是如何在自适应对话框中进行转换。 I tried to include the following code in the HttpRequest block but got the error "XmlDocument is a type, which is not valid in the given context."我试图在 HttpRequest 块中包含以下代码,但收到错误“XmlDocument 是一种类型,在给定的上下文中无效。” It seems like you cannot add your own customized codes in the adaptive dialog, what you can do is only using what the template can offer, but right now the HttpRequest class does not have an option for parsing XML response.似乎您无法在自适应对话框中添加自己的自定义代码,您只能使用模板可以提供的内容,但现在 HttpRequest class 没有解析 XML 响应的选项。 Can anyone please give me some guidance on this?谁能给我一些指导? Thanks!谢谢!

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

string json = JsonConvert.SerializeXmlNode(doc);

Codes to make the HttpRequest in the adaptive dialog:在自适应对话框中生成 HttpRequest 的代码:

new IfCondition()
{
    Condition = "conversation.Id != null",
    Actions = new List<Dialog>()
    {
        new HttpRequest()
        {
            Url = "http://api.openweathermap.org/data/2.5/weatherq=Detroit&mode=xml&appid=appid={your api key}",
            ResultProperty = "dialog.httpResponse",
            Method = HttpRequest.HttpMethod.GET,
            ResponseType = HttpRequest.ResponseTypes.Json
        },
        new Send Activity("${dialog.httpResponse}"),
        new Send Activity("${dialog.httpResponse.content}")
    }
}

The following shows what the HttpRequest response looks like.下面显示了 HttpRequest 响应的样子。 The OpenWeather API response (XML format) is converted into a string as the value of 'content'. OpenWeather API 响应(XML 格式)被转换为字符串作为“内容”的值。

{
    "statusCode": 200,
    "reasonPhrase": "OK",
    "headers": 
    {
        "Server": "openresty",
        "Date": "Tue, 14 Jul 2020 18:57:41 GMT",
        "Connection": "keep-alive",
        "X-Cache-Key": "/data/2.5/weather?mode=xml&q=detroit",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Credentials": "true",
        "Access-Control-Allow-Methods": "GET, POST"
    },
    "content": "<?xml version="1.0" encoding="UTF-8"?>\n
                <current>
                    <city id="4990729" name="Detroit">
                        <coord lon="-83.05" lat="42.33"></coord> 
                        <country>US</country>
                        <timezone>-14400</timezone>
                        <sun rise="2020-07-14T10:08:16" set="2020-07-15T01:07:33"></sun>
                    </city>
                    <temperature value="301.11" min="300.15" max="302.59" unit="kelvin"></temperature>
                    <feels_like value="301.1" unit="kelvin"></feels_like> 
                    <humidity value="44" unit="%"></humidity>
                    <pressure value="1019" unit="hPa"></pressure>
                    <wind>
                        <speed value="2.1" unit="m/s" name="Light breeze"></speed>
                        <gusts></gusts>
                        <direction></direction>
                    </wind>
                    <clouds value="75" name="broken clouds"></clouds>
                    <visibility value="16093"></visibility>
                    <precipitation mode="no"></precipitation>
                    <weather number="803" value="broken clouds" icon="04d"></weather>
                    <lastupdate value="2020-07-14T18:57:41"></lastupdate> 
               </current>"
}

You can use a code action.您可以使用代码操作。

new IfCondition()
{
    Condition = "conversation.Id != null",
    Actions = new List<Dialog>()
    {
        new HttpRequest()
        {
            Url = "http://api.openweathermap.org/data/2.5/weatherq=Detroit&mode=xml&appid=appid={your api key}",
            ResultProperty = "dialog.httpResponse",
            Method = HttpRequest.HttpMethod.GET,
            ResponseType = HttpRequest.ResponseTypes.Json
        },
        new CodeAction(async (dc, options) =>
        {
            var xml = dc.State.GetValue("dialog.httpResponse.content", () => "<root></root>");
            var doc = new XmlDocument();

            doc.LoadXml(xml);

            var json = JsonConvert.SerializeXmlNode(doc);

            dc.State.SetValue("dialog.json", json);

            return await dc.EndDialogAsync();
        }),
        new SendActivity("${dialog.json}"),
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM