简体   繁体   English

仅在Json.Net中的反序列化时忽略空值

[英]Only Ignore nulls on deserialization in Json.Net

When I have the following model: 当我有以下型号时:

public class Customer
{
    public Customer()
    {
        FirstName = string.Empty;
        LastName = string.Empty;
    }

    [JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
    public string FirstName {get;set;}

    [JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
    public string LastName {get;set;}
}

And that works great for when I'm posting data: 这对我发布数据非常有用:

// {
//    firstName: null,
//    lastName: null
// }

public int Post([FromBody]Customer customer)
{
    var firstName = customer.FirstName; //  <-- value is ""
}

The problem with this is that if the developer forgets in this system to initialize the data, then the response structure will leave it out: 这样做的问题是,如果开发人员忘记在这个系统中初始化数据,那么响应结构会将其遗漏:

public Customer
{
    FirstName = "";
}

// {
//    firstName: ''
// }

Basically, I don't want the values to be null but I also don't want to require the user to add an optional parameter in the request. 基本上,我不希望值为null,但我也不希望要求用户在请求中添加可选参数。 I can't use [Require] because it doesn't satisfy that second part. 我不能使用[Require]因为它不满足第二部分。

How it is set up now the onus is on the developer to initialize the property or else it will be omitted. 如何设置现在开发人员有责任初始化属性,否则将被省略。 Is there a way to accomplish this so that it only ignores for deserialization and not serialization? 有没有办法实现这一点,以便它只忽略反序列化而不是序列化?

If I might rephrase your question, you appear to be asking, How can I have a property of a type that always has a default, non-null value even when set to null when deserializing JSON or when uninitialized in application code? 如果我可以改写你的问题,你似乎在问:如果在反序列化JSON时或在应用程序代码中未初始化时,即使设置为null我怎么能拥有一个总是有一个默认的非null值的属性? If this rephrasing is correct, this can be handled by the type itself by using explicit rather than automatic properties: 如果这个改述是正确的,那么可以通过使用显式而不是自动属性来处理类型本身:

public class Customer
{
    string firstName = "";
    string lastName = "";

    public Customer() { }

    public string FirstName { get { return firstName; } set { firstName = value ?? ""; } }

    public string LastName { get { return lastName; } set { lastName = value ?? ""; } }
}

FirstName and LastName are now guaranteed to be non-null no matter how the Customer class is constructed. 无论Customer类是如何构造的, FirstNameLastName现在都保证为非null。

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

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