我正在编写一个自定义模型绑定器,有时需要处理表单。这些形式可能有数组作为值。 我一直在用这个方法
private static async Task HandleFormAsync(HttpContext httpContext, ModelBindingContext bindingContext)
{
var form = await httpContext.Request.ReadFormAsync();
string jsonString = $"{{{string.Join(",", form.Select(x => $"\"{x.Key}\" : \"{x.Value}\""))}}}";
try
{
var what = ProcessArray(jsonString);
PagedRequest pagedRequest = what?.ToObject<PagedRequest>();
if (string.IsNullOrEmpty(jsonString))
{
bindingContext.Result = ModelBindingResult.Failed();
return;
}
// Convert the form value to the target model type
var model = JsonConvert.DeserializeObject(jsonString, bindingContext.ModelType);
bindingContext.Result = ModelBindingResult.Success(model);
return;
}
catch (JsonException)
{
// Deserialization failed, possibly due to invalid JSON
bindingContext.Result = ModelBindingResult.Failed();
return;
}
}
它并没有获取数组值。 例如,json 如下所示:
{"filterList[0].filterType" : "contains","filterList[0].filterDataType" : "string","filterList[0].field" : "firstName","filterList[0].filterValue" : "bob","filterList[1].filterType" : "starts_with","filterList[1].filterDataType" : "string","filterList[1].field" : "lastName","filterList[1].filterValue" : "dylan","pageSize" : "15","pageNumber" : "1"}
正则表达式能否更好地解析数组值?
我试过这个
["](?<arrayName>\w+\[\d+\])\.(?<propertyName>\w+)["]\s*[:]\s*["](?<value>.*?)["][,}]
但它与第一个值不匹配
只是粗体值
{"filterList[0].filterType":包含,"filterList[0].filterDataType":"string","filterList[0].field":"firstName","filterList[0].filterValue": “bob”,“filterList[1].filterType”:“starts_with”,“filterList[1].filterDataType”:“字符串”,“filterList[1].field”:“lastName”,“filterList[1].filterValue” :“迪伦”}
有什么想法可以解决这个问题吗?
我不是 .NET 程序员,但我想知道为什么你需要转换 将您的表单转换为 JSON,然后再次解析它。这个不能用吗
form
对象来生成模型,而不需要这个 JSON 步骤?
关于正则表达式本身,您可以尝试一下这个注释模式 (使用 x 标志):
# JSON object key:
"(?:
# A) An array with its index and child property.
# Example: "filterList[0].filterType"
(?<arrayName>\w+\[(?<index>\d+)\])\.(?<propertyName>\w+)
|
# B) A simple key (not an array).
# Example: "pageSize" or "pageNumber"
(?<simpleProperty>\w+)
)"
\s*:\s* # Key and value separator.
"(?<value>.*?)" # JSON object value:
\s*[,}] # Separator or end of object.
PS:上面的语法着色可能是错误的,因为它没有检测到它是什么。
您将在这里获得更好的视图和详细信息:https://regex101.com/r/vANW9d/1