在 Newtonsoft JSON.NET 模式中禁用空类型
Disabling null type in Newtonsoft JSON.NET schema
我有一个 MVC 应用程序,它将我的模型序列化为 json 模式(使用 Newtonsoft json.net 模式)。问题是我的数组中的项具有类型 ["string", "null"]
,但我需要的只是 "string"
。这是我的 class:
的代码
public class Form
{
[Required()]
public string[] someStrings { get; set; }
}
这是由 Json.net 架构制作的架构:
"someStrings": {
"type": "array",
"items": {
"type": [
"string",
"null"
]
}
}
虽然我很期待这个:
"someStrings": {
"type": "array",
"items": {
"type": "string"
}
}
请帮我摆脱那个 "null"。
尝试在生成架构时将 DefaultRequired
设置为 DisallowNull
:
JSchemaGenerator generator = new JSchemaGenerator()
{
DefaultRequired = Required.DisallowNull
};
JSchema schema = generator.Generate(typeof(Form));
schema.ToString();
输出:
{
"type": "object",
"properties": {
"someStrings": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
你可以试试这个:
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
试试这个::
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public decimal? Salary { get; set; }
}
Employee employee= new Employee
{
Name = "Heisenberg",
Age = 44
};
string jsonWithNullValues = JsonConvert.SerializeObject(person, Formatting.Indented);
输出:空值
// {
// "Name": "Heisenberg",
// "Age": 44,
// "Salary": null
// }
string jsonWithOutNullValues = JsonConvert.SerializeObject(employee, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
输出:没有空值
// {
// "Name": "Heisenberg",
// "Age": 44
// }
我有一个 MVC 应用程序,它将我的模型序列化为 json 模式(使用 Newtonsoft json.net 模式)。问题是我的数组中的项具有类型 ["string", "null"]
,但我需要的只是 "string"
。这是我的 class:
public class Form
{
[Required()]
public string[] someStrings { get; set; }
}
这是由 Json.net 架构制作的架构:
"someStrings": {
"type": "array",
"items": {
"type": [
"string",
"null"
]
}
}
虽然我很期待这个:
"someStrings": {
"type": "array",
"items": {
"type": "string"
}
}
请帮我摆脱那个 "null"。
尝试在生成架构时将 DefaultRequired
设置为 DisallowNull
:
JSchemaGenerator generator = new JSchemaGenerator()
{
DefaultRequired = Required.DisallowNull
};
JSchema schema = generator.Generate(typeof(Form));
schema.ToString();
输出:
{
"type": "object",
"properties": {
"someStrings": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
你可以试试这个:
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
试试这个::
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public decimal? Salary { get; set; }
}
Employee employee= new Employee
{
Name = "Heisenberg",
Age = 44
};
string jsonWithNullValues = JsonConvert.SerializeObject(person, Formatting.Indented);
输出:空值
// {
// "Name": "Heisenberg",
// "Age": 44,
// "Salary": null
// }
string jsonWithOutNullValues = JsonConvert.SerializeObject(employee, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
输出:没有空值
// {
// "Name": "Heisenberg",
// "Age": 44
// }