Creating a JSON Schema from a Dynamic Object

I want to extract a JSON schema ( as defined here ) from an object of type dynamic.

This is the best example I could find .

But the JSON.NET schema generator must look at the actual class / type in order to be able to generate the schema.

Anyone have any ideas on how I can extract a circuit from a dynamic object?

+4
source share
2 answers

You can use JSON.NETto extract the schema JSONfrom a dynamic object. To do this, you only need the actual object of type dynamic. Try the following example:

dynamic person = new
            {
                Id = 1,
                FirstName = "John",
                LastName = "Doe"
            };

JsonSchemaGenerator schemaGenerator = new JsonSchemaGenerator {};

JsonSchema schema = schemaGenerator.Generate(person.GetType());

JSON :

{
    "type": "object",
    "additionalProperties": false,
    "properties": {
        "Id": {
            "required": true,
            "type": "integer"
        },
        "FirstName": {
            "required": true,
            "type": [
                "string",
                "null"
            ]
        },
        "LastName": {
            "required": true,
            "type": [
                "string",
                "null"
            ]
        }
    }
}
+8

.NET 4.0+, System.Web.Helpers.Json.Decode, JSON :

using System.Web.Helpers;
// convert json to a dynamic object:
var myObject = Json.Decode(json);

// or to go the other way and get json from a dynamic object:
string myJson = Json.Encode(myObject);

, "" "" Visual Studio 2012.

. JSON, .

-7

Source: https://habr.com/ru/post/1540620/


All Articles