来自动态JSON的表单构建器字段

时间:2018-04-12 10:44:58

标签: .net json botframework formflow

我想填充一个包含手动添加和动态添加的字段的表单。

public class ModelClass
{
    [Prompt("URL?")]
            public string URL { get; set; }
            [Prompt("Name?")]
            public string Title { get; set; }
}

Formbuilder:

 public IForm<ModelClass> BuildApplyform()
        {
            var builder = new FormBuilder<ModelClass>(); 
            // Parse string to json for usage in the foreach
            dynamic json = JObject.Parse(jsonString);

            builder.Message("Form builder");
            builder.Field(nameof(ModelClass.Title), active: (state) => false);
            builder.Field(nameof(ModelClass.URL), active: (state) => false);
            foreach(string param in json.Parameters)
            {
                builder.Field(param);
            }
            return builder.Build();
        }

JSONstring非常动态,每次都可以不同。但是,该字符串始终包含“d”和“parameter”子节点。 字符串可能如下所示:

"{
  \n\t\"d\":  {
    \n\t\t\"parameters\":  [
      {
        \n\t\t\t\"id\":  \"url\",
        \n\t\t\t\"name\":  \"Site URL\",
        \n\t\t\t\"required\":  \"text\"
      },
       {
        \n\t\t\t\"id\":  \"title\",
        \n\t\t\t\"URL\":  \"Title\",
        \n\t\t\t\"required\":  true,
        \n\t\t\t\"example\":  \"www.stackoverflow.com\"\n\t\t
      }
    ]\n\t
  }\n
}"

如何确保无论JSON的外观如何,参数都会在表单构建器中作为字段输入动态添加? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

<强>不能

好吧,经过一些研究,我发现实际上我想要达到的目标几乎是不可能的。 它不可能动态添加字段,并且可以与Bot Framework同时添加静态字段。因此,在这种情况下,formbuilder不是一个现实的可能性。正如Eric Dahlvang所说:只有通过JSON模式和表单构建器使用JSON才有可能。

我是如何解决这个问题的:

在我搜索使用表单构建器期间,我偶然发现了一个循环通过promptdialog的解决方案。可以读取JSON并将其转换为C#对象,以便您可以迭代它们,那么为什么不使用它呢?

全局定义字符串列表,或者我使用&#34;参数对象&#34;:

public class Parameter
{
    public string Id { get; set; }
    public string Title { get; set; }
    public bool Required { get; set; }
    public string Example { get; set; }
}

然后您必须获取JSON参数并将它们转换为C#对象(参数)。我使用全局List稍后访问params。然后我提示第一个问题(参数),以便循环开始。作业包含解析的JSON。

    public void SomeFunction(IDialogContext context)
{
        if (job["d"]["parameters"] != null)
                    {
                        var t = job["d"]["parameters"];
                        parameters = GetParametersFromJSON(t); // parameters is a globally defined list of <Parameter>
                    }
                    currentParameter = parameters[0];
                    PromptDialog.Text(context, ParamPrompt, "Please fill in: " + currentParameter.Title+ $", for example: {currentParameter.sampleValue}");
}



private async Task ParamPrompt(IDialogContext context, IAwaitable<string> 
result)
{
    var answer = await result;

        index++;
        if (index < parameters.Count)
        {
            currentParameter = parameters[index];
            PromptDialog.Text(context, ParamPrompt, "Please fill in: " + currentParameter.Title + $", for example: {currentParameter.example}");
        }
       else 
       {
           // handle logic, the loop is done.
       }
    }