我正在编写一个 C# 程序,以“此 JSON 模式”的形式导入 JSON 数据。该模式的作者选择将一些枚举类型实现为具有 const 字符串属性的对象数组,如下所示:
anyOf
和
"ApplicationType": {
"$id": "#ApplicationType",
"anyOf": [
{
"additionalProperties": false,
"properties": {
"description": {
"const": "Consent to make small (minor material) changes to a project with Planning Permission",
"type": "string"
},
"value": {
"const": "amendment.minorMaterial",
"type": "string"
}
},
"required": [
"value",
"description"
],
"type": "object"
},
{
"additionalProperties": false,
"properties": {
"description": {
"const": "Consent to make small (non-material) changes to a project with Planning Permission",
"type": "string"
},
"value": {
"const": "amendment.nonMaterial",
"type": "string"
}
},
"required": [
"value",
"description"
],
"type": "object"
},
NJsonSchema 将它们导入为具有可写字符串属性的对象,并且不导入 const 值。我想导入这些常量值,以便我可以验证和导入数据。我提出了三种解决方案,但我对其中任何一个都不是特别满意。作为枚举导入我可以将以上内容导入为以下带注释的枚举:
"FileType": {
"$id": "#FileType",
"anyOf": [
{
"additionalProperties": false,
"properties": {
"description": {
"const": "Elevations - existing",
"type": "string"
},
"value": {
"const": "elevations.existing",
"type": "string"
}
},
"required": [
"value",
"description"
],
"type": "object"
},
{
"additionalProperties": false,
"properties": {
"description": {
"const": "Elevations - proposed",
"type": "string"
},
"value": {
"const": "elevations.proposed",
"type": "string"
}
},
"required": [
"value",
"description"
],
"type": "object"
},
enum EApplicationType
{
[Code("amendment.minorMaterial")]
ConsentToMakeSmallMinorMaterialChangesToAProjectWithPlanningPermission,
[Code("amendment.nonMaterial")]
ConsentToMakeSmallNonMaterialChangesToAProjectWithPlanningPermission,
这样做的好处是每个列表都有自己的类型,但缺点是任何转换都必须使用反射,并且迭代所有值需要大量反射。我可以通过加载字典一次来解决这个问题。使用类和字符串属性我可以将值作为字符串导入到类中:
enum EFileType
{
[Code("elevations.existing")]
ElevationsExisting,
[Code("elevations.proposed")]
ElevationsProposed,
static class ApplicationType
{
public static string ConsentToMakeSmallMinorMaterialChangesToAProjectWithPlanningPermission => "amendment.minorMaterial";
public static string ConsentToMakeSmallNonMaterialChangesToAProjectWithPlanningPermission => "amendment.nonMaterial";
这里的优点是简单,我们将简单地比较字符串,但这最终不会被输入,我们将传递字符串而不是父类型。枚举所有值也需要再次反射。使用类/对象另一种选择是像 JSON 模式一样使用整个对象,如下所示:
static class FileType
{
public static string ElevationsExisting => "elevations.existing";
public static string ElevationsProposed => "elevations.proposed";
public class ConsentToDisplayAnAdvertisement : IApplicationType
{
public string Description => "ConsentToDisplayAnAdvertisement";
public string Value => "advertConsent";
public int CompareTo(object obj)
{
return Value.CompareTo((obj as IApplicationType).Value);
}
}
虽然这大部分有效,但使用带有对象的 public static class EEApplicationType
{
public static DescriptionValue ConsentToMakeSmallChangesToAProjectWithPlanningPermission = new DescriptionValue
(
"ConsentToMakeSmallChangesToAProjectWithPlanningPermission",
"amendment"
);
Corvus.JsonSchema 支持 const 值,并为您提供 Match() 函数来切换它们。