2015-05-17 33 views
1

我想從json數據文件生成json模式,如下所示(這是使用在線工具生成的,http://jsonschema.net/) 是否可以使用JSON.NET或其他?編程從JSON數據生成JSON模式

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

輸出:因爲我想生成它在程序運行我的目標是不使用工具

{ 
    "$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" 
      } 
     } 
     } 
    } 
    } 
} 

+0

HMM你是對的...它不是那麼容易......調查 –

回答

1

好,我這樣做:

  1. 下載的Visual Studio擴展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 framework 4.5項目(因爲這兩個程序集是用.net 4.5構建的,我沒有找到在網絡上其他地方的那些組件)
  6. 使用此代碼從您的JSON
  7. 得到JSON模式,雖然我不能保證給你,這種做法是合法的

-

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); 
+0

謝謝你的答案,但在你的解決方案的第一部分,它是一個代碼,我們沒有它。 (在字符串schemaJson = ...之前),理論上我們只有一個衆所周知的json文件,我們希望得到它Json Schema。 – eager

+0

現在好了我明白了,我會更新答案 –

+0

,所以我設法做到了 –