Reputation: 89
I am trying to get json schema from c# class file which has multiple classes.
I generated the c# class file (*.cs file) using xsd.exe and providing xml schema files (xsd files) (since main xsd has 2 imports so, has to give 2 other xsd files in same line in xsd.exe command)
ie, command to generate c# class file using xsd files
C:\Users\user1\jsonschema>xsd.exe /c main_1.xsd imported_1.xsd xml.xsd /o:C:\Users\user1\jsonschema\output\
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.3038]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\Users\user1\jsonschema\output\main_1_xml.cs'.
In main_1_xml.cs file, i can see multiple classes definition, now I need to convert this c# into json schema. I don't know how to do this part. Ideally am looking for one jsonschema outfile.
I admit am newbie c# so, don't know much of classes/serialization or other logic which converts c# classes into json format/schema.
Any help much appreciated.
[Edited: As per Zohar suggestion to inculde more details]
Basically have xsd file and using xsd.exe am generating c# class file. This class file has multiple sub classes/paritial class definitions. Now am trying to get this class definition into json schema format.
here is the c# class file content (have morethan 170 sub/parital classes definitions but simplicity kept only 2 :
using System.Xml.Serialization;
using System.Collections.Generic;
using Newtonsoft.Json;
//
// This source code was auto-generated by xsd, Version=2.0.50727.3038.
//
Filename : Program.cs
class Program // I have manually added this class and next line opening bracket for main class "Program"
{
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://example.org/content/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://example.org/content/2018/", IsNullable=false)]
public partial class newItem : AnyItemType {
private ContentMetadataAfDType contentMetaField;
private AssertType[] assertField;
private inlineRef[] inlineRefField;
private object[] items1Field;
private contentSet contentSetField;
/// <remarks/>
public ContentMetadataAfDType contentMeta {
get {
return this.contentMetaField;
}
set {
this.contentMetaField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("assert")]
public AssertType[] assert {
get {
return this.assertField;
}
set {
this.assertField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("inlineRef")]
public inlineRef[] inlineRef {
get {
return this.inlineRefField;
}
set {
this.inlineRefField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("derivedFrom", typeof(derivedFrom))]
[System.Xml.Serialization.XmlElementAttribute("derivedFromValue", typeof(derivedFromValue))]
public object[] Items1 {
get {
return this.items1Field;
}
set {
this.items1Field = value;
}
}
/// <remarks/>
public contentSet contentSet {
get {
return this.contentSetField;
}
set {
this.contentSetField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.example.org/content")]
[System.Xml.Serialization.XmlRootAttribute("internal", Namespace="http://www.example.org/0809/content", IsNullable=false)]
public partial class internalType {
private object[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("altId", typeof(altId), Namespace="http://example.org/content/2006-10-01/")]
[System.Xml.Serialization.XmlElementAttribute("audience", typeof(AudienceType), Namespace="http://example.org/content/2006-10-01/")]
[System.Xml.Serialization.XmlElementAttribute("contentMetaExtProperty", typeof(RSF_ContentMetaExtProperty_Flex2ExtPropType), Namespace="http://example.org/content/2006-10-01/")]
[System.Xml.Serialization.XmlElementAttribute("itemMetaExtProperty", typeof(RSF_ItemMetaExtProperty_Flex2ExtPropType), Namespace="http://example.org/content/2006-10-01/")]
[System.Xml.Serialization.XmlElementAttribute("subject", typeof(subject), Namespace="http://example.org/content/2006-10-01/")]
public object[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
} // I have manually added this close bracket for main class "Program"
in the same Program.cs file, I have add one more class and include main method and logic to generate json output using Newtonsoft
class json
{
/* below code to get the name of the classes from the namespace - was trying something
public Type[] GetTypesInNamespace(Assembly assembly, string nameSpace)
{
return
assembly.GetTypes()
.Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal))
.ToArray();
}
*/
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Program Generation = new Program();
var schemaGenerator = new Newtonsoft.Json.Schema.Generation.JSchemaGenerator();
schemaGenerator.GenerationProviders.Add(new Newtonsoft.Json.Schema.Generation.StringEnumGenerationProvider());
// if we give just main class name "Program, then in the out we get just 3 lines json format with type value as object"
var schema = schemaGenerator.Generate(typeof(JsonSchema.Program));
// if we pass-in main class and it's sub class name, then we get output of that sub class content as json format
//var schema = schemaGenerator.Generate(typeof(JsonSchema.Program.newsItem));
//Console.WriteLine(schema);
File.WriteAllText(@"Program1.json", schema.ToString());
//Program program = new Program();
//string strResultJson = JsonConvert.SerializeObject(program);
//File.WriteAllText(@"Program.json", strResultJson);
//Console.WriteLine("Worked!");
/*
logic to get the sub classnames and loop through inorder to all sub classes content as single json schema in one file
List<Type> theList = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace == "JsonSchema").ToList();
Console.WriteLine(theList);
//File.WriteAllText(@"Classnames.json", theList.ToString());
for (int i = 0; i < theList.Count; i++)
{
Console.WriteLine(theList[i].Name); // this gives full list of class names
File.WriteAllText(@"Classnames.json", theList[i].Name); // this writes only last classname, guess I need to figureout how to append
//File.WriteAllLines(@"Classnames.json", i);
}
*/
}
}
Upvotes: 1
Views: 4823
Reputation: 82474
It's really a very simple process:
You create an instance of JSchemaGenerator
,
(optional) add a new instance of StringEnumGenerationProvider
to it's GenerationProviders
collection,
and generate the schema from the c# type*:
var schemaGenerator = new Newtonsoft.Json.Schema.Generation.JSchemaGenerator();
schemaGenerator.GenerationProviders.Add(new Newtonsoft.Json.Schema.Generation.StringEnumGenerationProvider());
var schema = schemaGenerator.Generate(typeof(YourMainClassHere));
*Don't forget to change YourMainClassHere
to the actual name of the class.
This will generate the schema for the main class as well as any type of it's properties.
Update
Instead of enclosing all xsd-generated types inside a class, try creating a class that will use all these types as properties:
class Program
{
public newItem NewItem { get; set; }
public internalType InternalType { get; set; }
public AssertType AssertType { get; set; }
// Whatevet more types you need
}
Then, when you generate a schema for the Program
class, it will also contain all the properties if the xsd generated types as well.
Upvotes: 1