从JSON数据编程生成JSON模式

本文关键字:JSON 模式 编程 数据 | 更新日期: 2023-09-27 17:49:25

我想从json数据文件生成json模式,如下所示。(这是通过在线工具http://jsonschema.net/生成的)这是可能的JSON。NET还是其他的?

Json DataFile:

{
  "graph": [
    {
      "id": 453,
      "cid": 143,
      "title": "graph1",
      "description": "",
      "thumbnailPath": "art.jpg",
      "detailPath": "art.jpg",
      "link": "www.test.html",
      "author": "graph Team"
    },
    {
      "id": 12,
      "cid": 121,
      "title": "graph2",
      "description": "",
      "thumbnailPath": "art2.jpg",
      "detailPath": "art2.jpg",
      "link": "www.test2.html",
      "author": "graph Team"
    }
  ]
}
输出:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "/",
  "type": "object",
  "properties": {
    "graph": {
      "id": "graph",
      "type": "array",
      "items": {
        "id": "1",
        "type": "object",
        "properties": {
          "id": {
            "id": "id",
            "type": "integer"
          },
          "cid": {
            "id": "cid",
            "type": "integer"
          },
          "title": {
            "id": "title",
            "type": "string"
          },
          "description": {
            "id": "description",
            "type": "string"
          },
          "thumbnailPath": {
            "id": "thumbnailPath",
            "type": "string"
          },
          "detailPath": {
            "id": "detailPath",
            "type": "string"
          },
          "link": {
            "id": "link",
            "type": "string"
          },
          "author": {
            "id": "author",
            "type": "string"
          }
        }
      }
    }
  }
}

我的目标不是使用工具,因为我想在程序运行时生成它。

从JSON数据编程生成JSON模式

我这样做了:

  1. 下载visualstudio扩展https://visualstudiogallery.msdn.microsoft.com/b4515ef8-a518-41ca-b48c-bb1fd4e6faf7
  2. 将.vsix文件重命名为。zip
  3. 解压zip文件到任意文件夹
  4. 参考Microsoft.Json.SchemaExtension.dll和Microsoft.Json.SchemaProducer.dll
  5. 确保你的项目是一个。net框架4.5项目(因为这2个程序集是用。net 4.5构建的,我没有在网上其他地方找到这些程序集)
  6. 使用以下代码从JSON中获取JSON模式
  7. 虽然我不能向你保证这种方法是合法的

string json = @"{
  ""graph"": [
    {
      ""id"": 453,
      ""cid"": 143,
      ""title"": ""graph1"",
      ""description"": """",
      ""thumbnailPath"": ""art.jpg"",
      ""detailPath"": ""art.jpg"",
      ""link"": ""www.test.html"",
      ""author"": ""graph Team""
    },
    {
      ""id"": 12,
      ""cid"": 121,
      ""title"": ""graph2"",
      ""description"": """",
      ""thumbnailPath"": ""art2.jpg"",
      ""detailPath"": ""art2.jpg"",
      ""link"": ""www.test2.html"",
      ""author"": ""graph Team""
    }
  ]
}";
string jsonSchema = Microsoft.Json.SchemaProducer.SchemaBuilder.CreateSchema(json);