繁体   English   中英

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

[英]Model Binding with Nested JSON Objects

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

{
    id: "123456",
    user: {
        "name": {
            "first": "John",
            "Last": "Doe"
        }
    },
    "payment": {
        "type": "cash"
    }
}

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

public class SalesRecord
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public string PaymentType {get; set;}
}

端点示例(目前还不多):

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

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

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

使用此处提供的演练

定制模型粘合剂样品

并使其适应这个问题。

下面的示例使用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;}
}

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

SalesRecordBinder用于通过尝试使用自定义JSON转换器解析发布的内容来绑定SalesRecord参数,以简化去酶化。

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();
    }
}

来源:我可以在属性中指定一个路径,将我的类中的属性映射到我的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;
    }
}

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

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

    return BadRequest(ModelState);
}

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

注意 :这假定JSON输入始终有效。 如果不是这样,你将不得不添加一些检查。

如果您不想使其过于复杂,可以使用DLR的帮助。 NewtonSoft.Json序列化程序允许您反序列化为dynamic对象:

[HttpPost]
public IActionResult CreateSalesRecord([FromBody]dynamic salesRecord)
{
    return Ok(new SalesRecord
    {
        FirstName = salesRecord.user.name.first,
        LastName = salesRecord.user.name.Last,
        PaymentType = salesRecord.payment.type
    });
}
[HttpPost]
    public IActionResult Json(string json)
    {
        JObject j = JObject.Parse(json);
        MyModel m = j.ToObject<MyModel>();
        return View();
    }

如果你的Json是字符串格式,你可以尝试这个。 我相信它的工作你的数据模型必须是Json的精确表示。

暂无
暂无

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

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