asp.net 将非JSON字符串版本的Object转换为Object

c3frrgcw  于 2023-05-19  发布在  .NET
关注(0)|答案(1)|浏览(129)

如何将非JSON对象的字符串版本转换为对象类型?
我正在为这个结构体创建一个自定义的模型绑定器,这样我就可以将它作为查询参数发送:

[Serializable]
[ModelBinder(BinderType = typeof(DiscriminatorTagsBinder))]
public struct DiscriminatorTags : IDiscriminatorTags
{
    public DiscriminatorTags(List<int> tags, string discriminator, bool selected)
    {
        this.Tags = tags;
        this.Discriminator = discriminator;
        this.Selected = selected;
    }

    [Required]
    public List<int> Tags { get; set; }
    [Required]
    public string Discriminator { get; set; }
    [Required]
    public bool Selected { get; set; }
}

粘合剂:

public class DiscriminatorTagsBinder : IModelBinder
{

    public DiscriminatorTagsBinder()
    {
    }

    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        var modelName = bindingContext.ModelName;

        // Try to fetch the value of the argument by name
        var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);

    

        var x = JsonSerializer.Deserialize<DiscriminatorTags>(valueProviderResult.FirstValue);

        if (valueProviderResult == ValueProviderResult.None)
        {
            return Task.CompletedTask;
        }

        bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);

        var value = valueProviderResult.FirstValue;

        // Check if the argument value is null or empty
        if (string.IsNullOrEmpty(value))
        {
            return Task.CompletedTask;
        }

        bindingContext.Result = ModelBindingResult.Success(valueProviderResult);
        return Task.CompletedTask;
    }
}

要反序列化的值实际上不是JSON,而是对象的字符串版本:
“DiscriminatorTags(标签:[1、2、3、4、5、6、7、8、9、10、11、12、13、14、true,discriminator:GroceryItm)”
所以当我这样做的时候,我得到了一个JsonException:var x = JsonSerializer.Deserialize<DiscriminatorTags>(valueProviderResult.FirstValue);
如何将非json字符串转换为DiscriminatorTags结构类型?

cyej8jka

cyej8jka1#

这可能听起来很明显,但您必须手动解析字符串。这里没有免费的午餐。像这样的东西可以让你开始:

var str = "DiscriminatorTags(tags: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 900], selected: true, discriminator: GroceryItm)";
var matches = Regex.Matches(str, @"(tags:\s*\[(.*)\])|(selected:\s(true|false))|(discriminator:\s\w*)", RegexOptions.IgnoreCase);
var tagsMatch = matches[0].ValueSpan;
var bracketStartIndex = tagsMatch.IndexOf('[');
var tagsList = tagsMatch.Slice(bracketStartIndex + 1, tagsMatch.LastIndexOf(']') - 1 - bracketStartIndex);
var list = new List<int>();
foreach (var match in Regex.EnumerateMatches(tagsList, "[0-9]+"))
{
    list.Add(Convert.ToInt32(tagsList.Slice(match.Index, match.Length).ToString()));
}
var selectedMatch = matches[1];
var isSelected = Regex.Match(selectedMatch.Value, "true|false", RegexOptions.IgnoreCase);
var discriminatorMatch = matches[2].ValueSpan;
var discriminator = discriminatorMatch[(discriminatorMatch.IndexOf(':') + 1)..].Trim();

您需要加强它以防止丢失值等。并使用Regex的编译示例

相关问题