简体   繁体   English

JSON模式到C#类

[英]JSON schema to C# class

I am new to JSON, but I understand C# a bit. 我是JSON的新手,但我对C#有点了解。 I have a JSON schema and I ran across a part that I'm not sure how to put it in the objects class. 我有一个JSON模式,遇到了一个不确定如何将其放入对象类的部分。

"def_subscore": {
    "type": "number",
    "minimum": 0,
    "maximum": 10
},
"def_impact": {
    "type": "object",
    "properties": {
        "baseMetricV3": {
            "type": "object",
            "properties": {
                "cvssV3": {"$ref": "cvss-v3.0.json"},
                "exploitabilityScore": {"$ref": "#/definitions/def_subscore"},
                "impactScore": {"$ref": "#/definitions/def_subscore"}
            }
        }
    }
}

As we can see baseMetricV3 is a class object and defined with it's type and properties. 如我们所见, baseMetricV3是一个类对象,并使用其类型和属性进行定义。 exploitabilityScore is supposed to be a "Subscore" which is defined as a number with min and max limitations. exploitabilityScore应该是“ Subscore”,它定义为具有最小和最大限制的数字。

Can I make a class that acts like a double/integer and also has to pass class-specific validations? 我可以使类的行为类似于double / integer并且必须通过特定于类的验证吗?

Is the schema just saying exploitabilityScore and impactScore are just double/integers that require validation in my code to make sure the value falls between 0 and 10? 该模式是否只是在说exploitabilityScoreimpactScore只是double / integers,它们需要在我的代码中进行验证以确保该值介于0到10之间?

Or is the schema just saying exploitabilityScore and impactScore are just double/integers, by the way the data should never come through with values outside of 0 and 10 (as in the validation was already done on their side and the def_subscore was more of an informative)? 还是该模式只是说exploitabilityScoreimpactScore只是double / integers,顺便说一句,数据永远不要带有0和10以外的值(因为验证已经在他们这边完成了,而def_subscore更具参考价值) )?

If you schema says prop is of type number you have to define some double/int/float/... numerical type for that property and not a class. 如果你说的模式prop的类型为number ,你必须定义一些double/int/float/...数值类型为属性,而不是一类。

If you only want to check, whether a JSON object complies to the given schema, you can use some json validator library to validate the object against the schema. 如果只想检查JSON对象是否符合给定的架构,则可以使用一些json验证程序库针对该架构验证该对象。

Additionally, (or if you for instance parse a JSON string to a self defined class) you can use the RangeAttribute for your class 此外,(或者,例如,如果您将JSON字符串解析为自定义类), 则可以为类使用RangeAttribute

class SomeClass {
    [Range(1, 10)]
    public int SomeValue {get;set;}
}

For other constraints there may be other Annotations. 对于其他约束,可能会有其他注释。 You can even define them yourself like shown here https://stackoverflow.com/a/7256854/3776927 您甚至可以自己定义它们,如下所示:https://stackoverflow.com/a/7256854/3776927

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

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