反序列化与Json.NET:需要属性/键为present [英] Deserializing with Json.NET: Requiring a property/key to be present

查看:141
本文介绍了反序列化与Json.NET:需要属性/键为present的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 Json.NET 反序列化一个JSON字符串转换成一个对象,我怎么需要一个键/属性为present在JSON stirng,但允许NULL值?

When using Json.NET to deserialize a JSON string into an object, how do I require a key/property to be present in the JSON stirng, but allow for NULL values?

例如:

可以说我有一个类/对象...

Lets say I have a class/object...

[DataContract]
public class Car
{
    [DataMember(IsRequired = true)]
    public string Vin {get; set;}

    [DataMember(IsRequired = true)]
    public string Color {get; set;}

    public string Description {get; ;set}
}

在上面的例子中,VIN和颜色是必需的,如果任何一个人是从JSON字符串缺少一个异常会被抛出。但让说,Description属性是否具有反序列化后的值是可选的。换句话说NULL是一个有效的值。有两种方法可以做到这一点的JSON字符串:

In the above example, the VIN and Color are required, and an exception would be thrown if either one of them is missing from the JSON string. But lets say that whether or not the Description property has a value after being deserialized is optional. In other words NULL is a valid value. There are two ways to make this happen in the JSON string:

1)

{
    "vin": "blahblahblah7",
    "color": "blue",
    "description":  null
}

或 2)

{
    "vin": "blahblahblah7",
    "color": "blue"
}

现在的问题是,我不想假设描述值应为NULL,只是因为键/值对被排除在外的JSON字符串。我想JSON的发送者要明确它设置为NULL。如果场景#2发生这种情况,我想检测到它,并用一个错误消息作出回应。所以,我怎么要求的键/值对为present,但接受NULL作为一个值?

The problem is that I don't want to assume that the Description value should be NULL just because the key/value pair for the was left out of the JSON string. I want the sender of the JSON to be explicit about setting it to NULL. If scenario #2 were to happen, I want to detect it and respond with an error message. So how do I require the key/value pair to be present, but accept NULL as a value?

如果它可以帮助任何,我想一个的ASP.NET Web的范围内解决这个问题API 项目。

If it helps any, I'm trying to solve this problem within the context of an ASP.NET Web API project.

推荐答案

唉。我应该多花一点时间Json.NET文档中......

Ugh. I should have spend a little more time in the Json.NET documentation...

答案是的的必需属性 JsonPropertyAttribute ,这是枚举键入 Newtonsoft.Json.Required

The answer is the the Required property of the JsonPropertyAttribute, which is of enum type Newtonsoft.Json.Required

[JsonProperty(Required = Newtonsoft.Json.Required.AllowNull)]
public string Description {get; set;}

这篇关于反序列化与Json.NET:需要属性/键为present的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆