从动态对象生成JSON模式

时间:2014-05-15 01:59:25

标签: c# .net json json.net jsonschema

我想从 dynamic 类型的对象中提取JSON模式(as defined here)。

This is the best example I could find

但JSON.NET的Schema Generator需要查看实际的类/类型才能生成模式。

任何人对如何从动态对象中提取架构有任何想法?

2 个答案:

答案 0 :(得分:8)

您仍然可以使用JSON.NET从动态对象中提取JSON架构。你只需要一个动态类型的实际对象就可以做到这一点。请尝试以下示例:

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"
            ]
        }
    }
}

答案 1 :(得分:-7)

如果您使用的是.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样本,那就更清楚了。

相关问题