我有一个 .Net core Web API,它接受以下 JSON:(RequestModel)
{
"isSpecimen": true,
"forms": {
"cyber": {
"abc1": {
"formOrder": 1,
"endNumber": "1",
"selected": true,
"aggLimit": 5000000.0,
"Date": "2016-12-14T00:00:00.00Z"
},
"abc2": {
"formOrder": 2,
"endNumber": "4",
"selected": false,
"aggLimit": 50000.0,
"Date": "2019-12-14T00:00:00.00Z"
},
}
}
}
以下是模型类:
public class RequestModel
{
public FormsModel Forms { get; set; }
public bool IsSpecimen { get; set; }
}
public abstract class BaseFormInfo
{
public bool Selected { get; set; }
public int? FormOrder { get; set; }
public virtual string FormKey { get; set; }
}
public class FormsModel
{
public ExcessFormsModel? Excess { get; set; }
public CyberFormsModel? Cyber { get; set; }
}
public class CyberFormsModel
{
public Abc1? abc1 { get; set; }
public Abc2? abc2 { get; set; }
public Abc3? abc3 { get; set; }
}
public class Abc1: BaseFormInfo
{
public override string FormKey => "Abc1";
public decimal? aggLimit{ get; set; }
public DateTime? Date { get; set; }
public string? endNumber{ get; set; }
}
我想更新模型,将以下类的字段值设置为 NULL “已选择”:true
例如:“abc1”已“选择”:true
"cyber": {
"abc1": {
"formOrder": null,
"endNumber": null,
"selected": true,
"aggLimit": null,
"Date": null
},
}
如何迭代 JSON 数据以将值设置为 NULL?
您可以通过使用自定义模型绑定来完成此操作。首先将JSON字符串解析为JObject,然后遍历JSON结构找到cyber下的对象。对于每个网络,检查“selected”属性是否为true。如果是这样,请将除“selected”之外的所有属性设置为空。修改 JSON 后,将 JObject 重新转换为字符串。此外,您可以通过将 JsonIgnore 添加到 FormKey 属性来隐藏 FormKey。这是一个示例,您可以将其用作参考:
public abstract class BaseFormInfo
{
public bool Selected { get; set; }
public int? FormOrder { get; set; }
[JsonIgnore]
public virtual string FormKey { get; set; }
}
我的控制器:
[HttpPost]
public IActionResult Update([ModelBinder(typeof(MyModelBinder))] RequestModel request)
{
return Ok(request);
}
我的模型绑定器:
public class MyModelBinder : IModelBinder
{
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var jsonString = bindingContext.ActionContext.HttpContext.Request.Body;
using var reader = new StreamReader(jsonString);
var body = await reader.ReadToEndAsync();
if (string.IsNullOrEmpty(body))
{
return;
}
var inputJson = JObject.Parse(body);
var forms = inputJson["forms"];
var cyber = forms["cyber"];
foreach (var form in cyber)
{
if ((bool)form.First["selected"])
{
foreach (var property in form.First.Children<JProperty>())
{
if (property.Name != "selected")
{
property.Value = null;
}
}
}
}
var outputJson = inputJson.ToString();
var requestModel = JsonConvert.DeserializeObject<RequestModel>(outputJson);
bindingContext.Result = ModelBindingResult.Success(requestModel);
}
}