使用嵌套 JSON 对象进行模型绑定

Set*_*hMc 6 c# asp.net-core

我正在编写一个端点来接受来自第 3 方的 webhook 上的 POST 请求,并且他们发送的数据是 JSON 编码的正文。所以,我无法控制发送给我的数据,我需要处理它。我的问题是他们在他们的 JSON 中做了很多嵌套,因为我只使用了他们发送给我的几个键,我不想创建一堆不必要的嵌套模型来获取我想要的数据。这是一个示例有效负载:

{
    id: "123456",
    user: {
        "name": {
            "first": "John",
            "Last": "Doe"
        }
    },
    "payment": {
        "type": "cash"
    }
}
Run Code Online (Sandbox Code Playgroud)

我想把它放在一个看起来像这样的模型中:

public class SalesRecord
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public string PaymentType {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

端点示例(还没有多少):

[HttpPost("create", Name = "CreateSalesRecord")]
public ActionResult Create([FromBody] SalesRecord record)
{
    return Ok(record);
}
Run Code Online (Sandbox Code Playgroud)

我过去的工作是在 Phalcon PHP 框架中,我通常只是直接访问 POST Body 并自己在模型中设置值。我当然看到了模型绑定的优点,但我还不明白如何正确地解决这种情况。

Nko*_*osi 5

对于这样的场景,需要一个自定义模型绑定器。该框架允许这种灵活性。

使用此处提供的演练

自定义模型绑定示例

并使其适应这个问题。

以下示例使用模型ModelBinder上的属性SalesRecord

[ModelBinder(BinderType = typeof(SalesRecordBinder))]
[JsonConverter(typeof(JsonPathConverter))]
public class SalesRecord {
    [JsonProperty("user.name.first")]
    public string FirstName {get; set;}
    [JsonProperty("user.name.last")]
    public string LastName {get; set;}
    [JsonProperty("payment.type")]
    public string PaymentType {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

在前面的代码中,该ModelBinder属性指定了IModelBinder应该用于绑定SalesRecord操作参数的类型。

SalesRecordBinder用于将绑定SalesRecord通过试图解析使用自定义JSON转换器简化deseiralization发表的内容参数。

class JsonPathConverter : JsonConverter {
    public override object ReadJson(JsonReader reader, Type objectType, 
                                    object existingValue, JsonSerializer serializer) {
        JObject jo = JObject.Load(reader);
        object targetObj = Activator.CreateInstance(objectType);

        foreach (PropertyInfo prop in objectType.GetProperties()
                                                .Where(p => p.CanRead && p.CanWrite)) {
            JsonPropertyAttribute att = prop.GetCustomAttributes(true)
                                            .OfType<JsonPropertyAttribute>()
                                            .FirstOrDefault();

            string jsonPath = (att != null ? att.PropertyName : prop.Name);
            JToken token = jo.SelectToken(jsonPath);

            if (token != null && token.Type != JTokenType.Null) {
                object value = token.ToObject(prop.PropertyType, serializer);
                prop.SetValue(targetObj, value, null);
            }
        }
        return targetObj;
    }

    public override bool CanConvert(Type objectType) {
        // CanConvert is not called when [JsonConverter] attribute is used
        return false;
    }

    public override bool CanWrite {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, 
                                    JsonSerializer serializer) {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

来源:我可以在属性中指定路径以将类中的属性映射到 JSON 中的子属性吗?

public class SalesRecordBinder : IModelBinder {

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

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

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

        var json = valueProviderResult.FirstValue;

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

        //Try to parse the provided value into the desired model
        var model = JsonConvert.DeserializeObject<SalesRecord>(json);

        //Model will be null if unable to desrialize.
        if (model == null) {
            bindingContext.ModelState
                .TryAddModelError(
                    bindingContext.ModelName,
                    "Invalid data"
                );
            return Task.CompletedTask;
        }

        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, model);

        //could consider checking model state if so desired.

        //set result state of binding the model
        bindingContext.Result = ModelBindingResult.Success(model);
        return Task.CompletedTask;
    }
}
Run Code Online (Sandbox Code Playgroud)

从那里现在应该是在动作中使用模型的简单问题

[HttpPost("create", Name = "CreateSalesRecord")]
public IActionResult Create([FromBody] SalesRecord record) {
    if(ModelState.IsValid) {
        //...
        return Ok();
    }

    return BadRequest(ModelState);
}
Run Code Online (Sandbox Code Playgroud)

免责声明:这尚未经过测试。可能还有一些问题需要解决,因为它基于上面提供的链接源。