如何从具有多个 类 定义的 c# 文件生成 json 模式

how to generate json schema from c# file which has multiple classes definition

我正在尝试从 c# class 文件中获取 json 模式,该文件具有多个 classes。

我使用 xsd.exe 生成了 c# class 文件(*.cs 文件)并提供 xml 模式文件(xsd 文件)(因为 main xsd 有 2 个导入,因此必须在 xsd.exe 命令的同一行中提供另外 2 个 xsd 文件)

即,使用 xsd 文件生成 c# class 文件的命令

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'.

在main_1_xml.cs文件中,我可以看到多个classes定义,现在我需要将这个c#转换成json模式。我不知道该怎么做。理想情况下我正在寻找一个 jsonschema 输出文件。

我承认我是 c# 新手,所以,不太了解 classes/serialization 或其他将 c# classes 转换为 json format/schema.[=16 的逻辑=]

非常感谢任何帮助。

[编辑:根据 Zohar 的建议以包含更多详细信息]

基本上有 xsd 文件并使用 xsd.exe 生成 c# class 文件。这个 class 文件有多个子 classes/paritial class 定义。现在我正在尝试将此 class 定义转换为 json 架构格式。

这里是 c# class 文件内容(有超过 170 sub/parital classes 定义,但简单性只保留 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.
// 

文件名: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"

在同一个 Program.cs 文件中,我又添加了一个 class 并包含使用 Newtonsoft

生成 json 输出的主要方法和逻辑
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);
            }
        */

        }
    }

这真的是一个非常简单的过程:

您创建了 JSchemaGenerator
的实例 (可选)将 StringEnumGenerationProvider 的新实例添加到它的 GenerationProviders 集合中,
并从 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));

*不要忘记将 YourMainClassHere 更改为 class 的实际名称。

这将为主要 class 及其任何类型的属性生成架构。

更新
不要将所有 xsd 生成的类型包含在 class 中,而是尝试创建一个 class 将使用所有这些类型作为属性:

class Program 
{
    public newItem NewItem { get; set; }
    public internalType InternalType { get; set; }
    public AssertType AssertType { get; set; }
    // Whatevet more types you need
}

然后,当您为 Program class 生成架构时,如果 xsd 也生成了类型,它也将包含所有属性。