【问题标题】:Marking a property as Json Required with Newtonsoft just makes object null使用 Newtonsoft 将属性标记为必需的 Json 只会使对象为空
【发布时间】:2021-07-03 19:24:50
【问题描述】:

我的 API 有一个请求对象,我想强制我的属性始终存在于正文中。这是我的对象:

public class Code
{
    [JsonProperty("id", Required = Required.Always)]
    public string id { get; set; }

    [JsonProperty("type", Required = Required.Always)]
    public string type { get; set; }
}

但是,当我没有在我的请求正文中传递type 属性时,我的Code 对象为空。相反,我希望将错误的请求错误传播回客户端。 Newtonsoft 装饰器不会在这里为我这样做吗?还是我必须手动添加检查以查看属性是否为空?

【问题讨论】:

标签: c# json.net


【解决方案1】:

Fluent Validation 是您的解决方案。因此,您不必使用JsonProperty 属性。

用法:

首先,为您的类创建一个验证器。

public class CodelValidator : AbstractValidator<Code>
{
    public CodelValidator()
    {
        RuleFor(x => x.id).NotEmpty().WithMessage("id is required.");
        RuleFor(x => x.type).NotEmpty().WithMessage("type is required.");
    }
}

在你的控制器方法中:

public ActionResult TestMethod(Code code)
{
    var validator = new CodeValidator();
    var validationResult = await validator.ValidateAsync(code);
    if (validationResult.IsValid == false)
    {
        var errorMessages = validationResult.Errors.Select(s => s.ErrorMessage);
        // manage how you want to show the erros.
    }
    ...
}

所以,当你得到所有的错误。现在你可以随心所欲地展示了。

【讨论】:

    【解决方案2】:

    https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1064

    目前 JsonProperty.Required 的值仅确定该值是否是必需的 - 它不允许您指示一个值可能为空,也可能不为空。

    此外,在查看代码时,所有空字符串似乎都被转换为 null

    https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs#L282

    【讨论】:

      【解决方案3】:

      以下代码按预期为我抛出:

      string serialized = @"{ 'noId': '123' }";  
      Code deserialized = JsonConvert.DeserializeObject<Code>(serialized);
      Console.WriteLine(deserialized.Id);
      

      我的代码类:

          class Code
          {
              [JsonProperty("id", Required = Required.Always)]
              public string Id { get; set; }
          }
      

      您能确认使用了 Newtonsoft.Json 吗?如果您使用的是 ASP.NET Core 3.x 或更高版本,请参考How to use Newtonsoft.Json as default in Asp.net Core Web Api? 将您的项目设置为使用Newtonsoft.Json

      【讨论】:

      • 是的,Newtonsoft 没有用作默认序列化程序,这似乎是个问题
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多