2016-04-15 16 views
1

我有一個對象誰是一個Json Schema(JSchema)的屬性。我如何序列化JSchema作爲另一個對象的一部分?

JSchema aSchema; 

object foo = new {propA = "x", schema = aSchema}; 

然而,當這是連載:

string str = JsonConvert.SerializeObject(foo); 

的JSchema對象連同其所有其他屬性...而不是一個乾淨的JSON模式序列化,像它的ToString()的輸出它只是發出Json Schema字符串。

我要的是序列化爲JSON模式的物體,像這樣的架構屬性:

{ 
    "propA": "x", 
    "schema": { 
     "id": "", 
     "description": "", 
     "definitions": { 
      "number": { 
       "type": "number" 
      }, 
      "string": { 
       "type": "string" 
      } 
     }, 
     "properties": { 
      "title": { 
       "title": "Title", 
       "type": "string" 
      } 
     } 
    } 
} 

你會怎麼做呢?

+1

看到您目前正在更好地理解問題的輸出會有所幫助。 –

+0

把你的JSON模式類或把你想要的輸出。 –

回答

0
public class Number 
{ 
    public string type { get; set; } 
} 
public class String 
{ 
    public string type { get; set; } 
} 
public class Definitions 
{ 
    public Number number { get; set; } 
    public String @string { get; set; } 
} 
public class Title 
{ 
    public string title { get; set; } 
    public string type { get; set; } 
} 
public class Properties 
{ 
    public Title title { get; set; } 
} 
public class Schema 
{ 
    public string id { get; set; } 
    public string description { get; set; } 
    public Definitions definitions { get; set; } 
    public Properties properties { get; set; } 
} 
public class RootObject 
{ 
    public string propA { get; set; } 
    public Schema schema { get; set; } 
} 

Serialize方法

dynamic coll = new 
{ 
    Root = new RootObject() 
    { 
     propA = "x",    
     schema = new Schema 
     { 
      id = "", 
      description = "", 
      definitions = new Definitions() 
      { 
       number = new Number() 
       { 
        type = "number" 
       }, 
       @string = new String() 
       { 
        type = "number" 
       } 
      }, 
      properties = new Properties() 
      { 
       title = new Title() 
       { 
        title = "Title", 
        type = "string" 
       } 
      } 
     } 
    } 
}; 

var output = JsonConvert.SerializeObject(coll); 

的Fiddler:https://dotnetfiddle.net/f2wG2G

更新

var jsonSchemaGenerator = new JsonSchemaGenerator(); 
var myType = typeof(RootObject); 

var schema = jsonSchemaGenerator.Generate(myType); 
schema.Id = ""; 
schema.Description = ""; 
schema.Title = myType.Name; 

的Fiddler:https://dotnetfiddle.net/FwJX69

+0

我明白如何從上面顯示的自定義對象中創建Json輸出。但是,正如我在帖子中提到的,我正在使用一個JSchema對象,該對象具有許多其他屬性等... –

+0

將您的JSON模式類。 –

相關問題