### Define Schema Example using XML Docs Source: https://github.com/ricosuter/njsonschema/wiki/XML-Documentation Use the `/// ` tag in your C# code to define an example for a schema property. This example will be included in the generated JSON Schema or Swagger/OpenAPI documentation. ```csharp /// /// { "name": "Smith" } /// public class Person { public string Name { get; set; } ``` -------------------------------- ### PayPal Subscription Creation Response Example Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.Tests/Deserialization/Snapshots/DeserializationTests.CanRoundTripPayPalOpenApi.verified.txt Example JSON response for creating a PayPal subscription. It includes details like subscription ID, status, plan ID, and subscriber information. ```json { "id": "I-BW452GLLEP1G", "status": "APPROVAL_PENDING", "status_update_time": "2018-12-10T21:20:49Z", "plan_id": "P-5ML4271244454362WXNWU5NQ", "plan_overridden": false, "start_time": "2018-11-01T00:00:00Z", "quantity": "20", "shipping_amount": { "currency_code": "USD", "value": "10.00" }, "subscriber": { "name": { "given_name": "John", "surname": "Doe" }, "email_address": "customer@example.com", "payer_id": "2J6QB8YJQSJRJ", "shipping_address": { "name": { "full_name": "John Doe" }, "address": { "address_line_1": "2211 N First Street", "address_line_2": "Building 17", "admin_area_2": "San Jose", "admin_area_1": "CA", "postal_code": "95131", "country_code": "US" } } }, "create_time": "2018-12-10T21:20:49Z", "links": [ { "href": "https://www.paypal.com/webapps/billing/subscriptions?ba_token=BA-2M539689T3856352J", "rel": "approve", "method": "GET" }, { "href": "https://api-m.paypal.com/v1/billing/subscriptions/I-BW452GLLEP1G", "rel": "edit", "method": "PATCH" }, { "href": "https://api-m.paypal.com/v1/billing/subscriptions/I-BW452GLLEP1G", "rel": "self", "method": "GET" } ] } ``` -------------------------------- ### PayPal Plan Request POST Example Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.Tests/Deserialization/Snapshots/DeserializationTests.CanRoundTripPayPalOpenApi.verified.txt Example of a POST request for creating a PayPal billing plan. It includes product details, billing cycles, pricing, payment preferences, and tax information. ```json { "product_id": "PROD-XXCD1234QWER65782", "name": "Video Streaming Service Plan", "description": "Video Streaming Service basic plan", "status": "ACTIVE", "billing_cycles": [ { "frequency": { "interval_unit": "MONTH", "interval_count": 1 }, "tenure_type": "TRIAL", "sequence": 1, "total_cycles": 2, "pricing_scheme": { "fixed_price": { "value": "3", "currency_code": "USD" } } }, { "frequency": { "interval_unit": "MONTH", "interval_count": 1 }, "tenure_type": "TRIAL", "sequence": 2, "total_cycles": 3, "pricing_scheme": { "fixed_price": { "value": "6", "currency_code": "USD" } } }, { "frequency": { "interval_unit": "MONTH", "interval_count": 1 }, "tenure_type": "REGULAR", "sequence": 3, "total_cycles": 12, "pricing_scheme": { "fixed_price": { "value": "10", "currency_code": "USD" } } } ], "payment_preferences": { "auto_bill_outstanding": true, "setup_fee": { "value": "10", "currency_code": "USD" }, "setup_fee_failure_action": "CONTINUE", "payment_failure_threshold": 3 }, "taxes": { "percentage": "10", "inclusive": false } } ``` -------------------------------- ### PayPal Pricing Schemes Example Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.Tests/Deserialization/Snapshots/DeserializationTests.CanRoundTripPayPalOpenApi.verified.txt Example of pricing schemes for PayPal, including fixed-price and tiered pricing models. This structure is used when defining billing plans. ```json { "pricing_schemes": [ { "billing_cycle_sequence": 1, "pricing_scheme": { "fixed_price": { "value": "50", "currency_code": "USD" } } }, { "billing_cycle_sequence": 2, "pricing_scheme": { "fixed_price": { "value": "100", "currency_code": "USD" }, "pricing_model": "VOLUME", "tiers": [ { "starting_quantity": "1", "ending_quantity": "1000", "amount": { "value": "150", "currency_code": "USD" } }, { "starting_quantity": "1001", "amount": { "value": "250", "currency_code": "USD" } } ] } } ] } ``` -------------------------------- ### Generate Schemas Respecting XML Documentation Comments Source: https://context7.com/ricosuter/njsonschema/llms.txt Configure your .NET project to emit XML documentation files. NJsonSchema will then read , , and tags and populate the schema's description and example fields accordingly. ```csharp // In MyProject.csproj: // true /// Represents a customer account. /// /// { "id": 1, "email": "user@example.com" } /// public class Customer { /// Unique identifier. public int Id { get; set; } /// Customer email address. public string Email { get; set; } } var schema = JsonSchema.FromType(); Console.WriteLine(schema.Description); // "Represents a customer account." Console.WriteLine(schema.Example?.ToString()); // { "id": 1, "email": "user@example.com" } Console.WriteLine(schema.Properties["Id"].Description); // "Unique identifier." ``` -------------------------------- ### Create PayPal Billing Plan Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.Tests/Deserialization/Snapshots/DeserializationTests.CanRoundTripPayPalOpenApi.verified.txt Use this example to create a new billing plan for PayPal subscriptions. It defines trial and regular pricing cycles. ```json { "id": "P-5ML4271244454362WXNWU5NQ", "product_id": "PROD-XXCD1234QWER65782", "name": "Video Streaming Service Plan", "description": "Video Streaming Service basic plan", "status": "ACTIVE", "billing_cycles": [ { "frequency": { "interval_unit": "MONTH", "interval_count": 1 }, "tenure_type": "TRIAL", "sequence": 1, "total_cycles": 2, "pricing_scheme": { "fixed_price": { "value": "3", "currency_code": "USD" }, "version": 1, "create_time": "2020-05-27T12:13:51Z", "update_time": "2020-05-27T12:13:51Z" } }, { "frequency": { "interval_unit": "MONTH", "interval_count": 1 }, "tenure_type": "TRIAL", "sequence": 2, "total_cycles": 3, "pricing_scheme": { "fixed_price": { "currency_code": "USD", "value": "6" }, "version": 1, "create_time": "2020-05-27T12:13:51Z", "update_time": "2020-05-27T12:13:51Z" } }, { "frequency": { "interval_unit": "MONTH", "interval_count": 1 }, "tenure_type": "REGULAR", "sequence": 3, "total_cycles": 12, "pricing_scheme": { "fixed_price": { "currency_code": "USD", "value": "10" }, "version": 1, "create_time": "2020-05-27T12:13:51Z", "update_time": "2020-05-27T12:13:51Z" } } ], "payment_preferences": { "auto_bill_outstanding": true } } ``` -------------------------------- ### Serialized JSON Object Example Source: https://github.com/ricosuter/njsonschema/wiki/Inheritance An example of a serialized Container object, demonstrating the 'discriminator' field identifying the 'Dog' subclass. ```json { "Animal": { "discriminator": "Dog", "Bar": "bar", "Foo": "foo" } } ``` -------------------------------- ### Disable AllowNullableBodyParameters for Examples Source: https://github.com/ricosuter/njsonschema/wiki/XML-Documentation To ensure examples are shown on the Swagger UI, set `AllowNullableBodyParameters` to `false`. If not disabled, only a null/empty example will be generated. ```csharp settings.GeneratorSettings.AllowNullableBodyParameters = false; ``` -------------------------------- ### Create Subscription Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.Tests/Deserialization/Snapshots/DeserializationTests.CanRoundTripPayPalOpenApi.verified.txt Creates a new subscription for a customer. This endpoint allows for the configuration of subscription plans, start times, quantities, shipping details, and application context. ```APIDOC ## POST /v1/billing/subscriptions ### Description Creates a new subscription. ### Method POST ### Endpoint /v1/billing/subscriptions ### Request Body - **plan_id** (string) - Required - The ID of the subscription plan. - **start_time** (string) - Required - The desired start time for the subscription in ISO 8601 format. - **quantity** (string) - Optional - The quantity of the subscription. - **shipping_amount** (object) - Optional - The amount for shipping. - **currency_code** (string) - Required - The currency code (e.g., USD). - **value** (string) - Required - The shipping amount value. - **subscriber** (object) - Required - Information about the subscriber. - **name** (object) - Required - The name of the subscriber. - **given_name** (string) - Required - The given name. - **surname** (string) - Required - The surname. - **email_address** (string) - Required - The email address of the subscriber. - **shipping_address** (object) - Optional - The shipping address of the subscriber. - **name** (object) - Required - The name for shipping. - **full_name** (string) - Required - The full name. - **address** (object) - Required - The address details. - **address_line_1** (string) - Required - The first line of the address. - **address_line_2** (string) - Optional - The second line of the address. - **admin_area_2** (string) - Required - The city or locality. - **admin_area_1** (string) - Required - The state or province. - **postal_code** (string) - Required - The postal code. - **country_code** (string) - Required - The two-letter country code. - **application_context** (object) - Optional - Context for the application. - **brand_name** (string) - Optional - The brand name. - **locale** (string) - Optional - The locale (e.g., en-US). - **shipping_preference** (string) - Optional - Shipping preference. - **user_action** (string) - Optional - User action. - **payment_method** (object) - Optional - Payment method details. - **payer_selected** (string) - Optional - Payer selected payment method. - **payee_preferred** (string) - Optional - Payee preferred payment method. - **return_url** (string) - Optional - The URL to return to after payment. - **cancel_url** (string) - Optional - The URL to cancel the subscription. ### Request Example { "plan_id": "P-5ML4271244454362WXNWU5NQ", "start_time": "2018-11-01T00:00:00Z", "quantity": "20", "shipping_amount": { "currency_code": "USD", "value": "10.00" }, "subscriber": { "name": { "given_name": "John", "surname": "Doe" }, "email_address": "customer@example.com", "shipping_address": { "name": { "full_name": "John Doe" }, "address": { "address_line_1": "2211 N First Street", "address_line_2": "Building 17", "admin_area_2": "San Jose", "admin_area_1": "CA", "postal_code": "95131", "country_code": "US" } } }, "application_context": { "brand_name": "walmart", "locale": "en-US", "shipping_preference": "SET_PROVIDED_ADDRESS", "user_action": "SUBSCRIBE_NOW", "payment_method": { "payer_selected": "PAYPAL", "payee_preferred": "IMMEDIATE_PAYMENT_REQUIRED" }, "return_url": "https://example.com/returnUrl", "cancel_url": "https://example.com/cancelUrl" } } ### Response #### Success Response (200) - **schema** (object) - Reference to the subscription schema. #### Response Example (Response details depend on the subscription schema) ``` -------------------------------- ### TypeScript Class Generation Example Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.TypeScript.Tests/Snapshots/ClassGenerationTests.Verify_output_style=Class.verified.txt Demonstrates the `toJSON` method of a generated TypeScript class, showing how it serializes complex data structures including dates, arrays, and nested objects. ```typescript data = typeof data === 'object' ? data : {}; data["Name"] = this.name; data["DateOfBirth"] = this.dateOfBirth ? this.dateOfBirth.toISOString() : undefined as any; if (Array.isArray(this.primitiveArray)) { data["PrimitiveArray"] = []; for (let item of this.primitiveArray) data["PrimitiveArray"].push(item); } if (this.primitiveDictionary) { data["PrimitiveDictionary"] = {}; for (let key in this.primitiveDictionary) { if (this.primitiveDictionary.hasOwnProperty(key)) (data["PrimitiveDictionary"] as any)[key] = (this.primitiveDictionary as any)[key]; } } if (Array.isArray(this.dateArray)) { data["DateArray"] = []; for (let item of this.dateArray) data["DateArray"].push(item.toISOString()); } if (this.dateDictionary) { data["DateDictionary"] = {}; for (let key in this.dateDictionary) { if (this.dateDictionary.hasOwnProperty(key)) (data["DateDictionary"] as any)[key] = this.dateDictionary[key] ? this.dateDictionary[key].toISOString() : undefined as any; } } data["Reference"] = this.reference ? this.reference.toJSON() : undefined as any; if (Array.isArray(this.array)) { data["Array"] = []; for (let item of this.array) data["Array"].push(item ? item.toJSON() : undefined as any); } if (this.dictionary) { data["Dictionary"] = {}; for (let key in this.dictionary) { if (this.dictionary.hasOwnProperty(key)) (data["Dictionary"] as any)[key] = this.dictionary[key] ? this.dictionary[key].toJSON() : undefined as any; } } return data; } export interface IMyClass { name: string | undefined; dateOfBirth: Date; primitiveArray: number[] | undefined; primitiveDictionary: { [key: string]: number; } | undefined; dateArray: Date[] | undefined; dateDictionary: { [key: string]: Date; } | undefined; reference: Student | undefined; array: Student[] | undefined; dictionary: { [key: string]: Student; } | undefined; } ``` -------------------------------- ### Generate Schema with System.Text.Json Source: https://context7.com/ricosuter/njsonschema/llms.txt Configure schema generation to use System.Text.Json instead of Newtonsoft.Json by setting SerializerOptions and leaving SerializerSettings null. This example shows generating a schema for an Order class with custom property naming. ```csharp using NJsonSchema.Generation; using System.Text.Json; using System.Text.Json.Serialization; public class Order { [JsonPropertyName("order_id")] public int OrderId { get; set; } [JsonIgnore] public string InternalNote { get; set; } } var settings = new SystemTextJsonSchemaGeneratorSettings { SerializerOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase } }; var schema = JsonSchema.FromType(settings); Console.WriteLine(schema.ToJson()); // "order_id" appears; "InternalNote" is absent ``` -------------------------------- ### CSharp Default Decimal Property Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/DefaultPropertyTests.When_generating_CSharp_code_then_default_value_with_decimal_generates_expected_expression.verified.txt Demonstrates a CSharp class with an optional decimal property initialized with a default value. This is useful when a property should have a specific starting value if not provided. ```csharp //---------------------- // // //---------------------- namespace MyNamespace { #pragma warning disable // Disable all warnings public partial class Anonymous { [Newtonsoft.Json.JsonProperty("someOptionalProperty", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public double SomeOptionalProperty { get; set; } = 123.456D; private System.Collections.Generic.IDictionary _additionalProperties; [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary AdditionalProperties { get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } set { _additionalProperties = value; } } } } ``` -------------------------------- ### Extend Generated TypeScript Classes Source: https://github.com/ricosuter/njsonschema/wiki/TypeScriptGenerator Provides an example of how to extend generated TypeScript classes with custom logic. Imports are handled, and the 'generated' import is preserved. Classes specified in 'ExtendedClasses' have their bodies copied, while the rest of the code is appended. ```typescript import generated = require("serviceClient"); // import generated from './serviceClient'; // also allowed // import * as generated from './serviceClient'; // also allowed class Person extends generated.Person { get name() { return this.firstName + " " + this.lastName; } } class Car extends generated.Car { } ``` -------------------------------- ### MyClass Initialization and Serialization Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.TypeScript.Tests/Snapshots/ConstructorInterfaceTests.When_constructor_interface_and_conversion_code_is_generated_then_it_is_correct.verified.txt Handles initialization and JSON serialization for a base class with various property types, including nested objects, arrays, and dictionaries. Includes logic for discriminator-based instantiation. ```typescript for (let key in _data["Bar"]) { if (_data["Bar"].hasOwnProperty(key)) (this.bar as any)![key] = _data["Bar"][key] ? _data["Bar"].map((i: any) => Skill.fromJS(i)) : []; } } } } static fromJS(data: any): MyClass { data = typeof data === 'object' ? data : {}; if (data["discriminator"] === "Student") { let result = new Student(); result.init(data); return result; } throw new Error("The abstract class 'MyClass' cannot be instantiated."); } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["discriminator"] = this._discriminator; data["Supervisor"] = this.supervisor ? this.supervisor.toJSON() : undefined as any; data["Address"] = this.address ? this.address.toJSON() : undefined as any; if (Array.isArray(this.cars)) { data["Cars"] = []; for (let item of this.cars) data["Cars"].push(item ? item.toJSON() : undefined as any); } if (this.skills) { data["Skills"] = {}; for (let key in this.skills) { if (this.skills.hasOwnProperty(key)) (data["Skills"] as any)[key] = this.skills[key] ? this.skills[key].toJSON() : undefined as any; } } if (Array.isArray(this.foo)) { data["Foo"] = []; for (let item of this.foo) data["Foo"].push(item); } if (this.bar) { data["Bar"] = {}; for (let key in this.bar) { if (this.bar.hasOwnProperty(key)) (data["Bar"] as any)[key] = (this.bar as any)[key]; } } return data; } } export interface IMyClass { supervisor: MyClass | undefined; address: IAddress | undefined; cars: ICar[] | undefined; skills: { [key: string]: ISkill; } | undefined; foo: Car[][] | undefined; bar: { [key: string]: Skill[]; } | undefined; } ``` -------------------------------- ### Generate Schema using SampleJsonSchemaGenerator Instance Source: https://github.com/ricosuter/njsonschema/wiki/SampleJsonSchemaGenerator Instantiate `SampleJsonSchemaGenerator` and use its `Generate` method to create a JSON Schema from sample JSON data. This provides an alternative to the static method. ```csharp var generator = new SampleJsonSchemaGenerator(); var schema = generator.Generate("..."); ``` -------------------------------- ### TypeScript Variable Declaration Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.TypeScript.Tests/Snapshots/ExtensionCodeTests.When_classes_have_extension_code_then_class_body_is_copied.verified.txt Declares a constant variable 'x' and initializes it with the value 10. This is a basic example of variable declaration in TypeScript. ```typescript var x = 10; ``` -------------------------------- ### C# Record with Constructor and Init Properties Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/GeneralGeneratorTests.When_csharp_record_init_in_record_and_constructor_provided.verified.txt Use this pattern for C# records that require a constructor for specific initialization logic while also allowing property updates via init setters after object creation. Ensure Newtonsoft.Json attributes are correctly applied for serialization. ```csharp //---------------------- // // //---------------------- namespace MyNamespace { #pragma warning disable // Disable all warnings public partial record Address { [Newtonsoft.Json.JsonConstructor] public Address(string @street, string @city) { this.Street = @street; this.City = @city; } [Newtonsoft.Json.JsonProperty("Street", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Street { get; init; } [Newtonsoft.Json.JsonProperty("City", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string City { get; init; } } } ``` -------------------------------- ### Transform JsonSerializerSettings Source: https://github.com/ricosuter/njsonschema/wiki/CSharpGeneratorSettings Example of a static method to transform JsonSerializerSettings. This method is called by the generator to customize serialization behavior, such as date parsing. ```csharp namespace MyNamespace { internal static class SerializerSettings { public static JsonSerializerSettings TransformSettings( JsonSerializerSettings settings) { settings.DateParseHandling = DateParseHandling.DateTimeOffset; return settings; } } } ``` -------------------------------- ### Configure JsonSchemaGenerator for System.Text.Json Source: https://github.com/ricosuter/njsonschema/wiki/JsonSchemaGenerator Shows how to configure the JsonSchemaGenerator to use System.Text.Json serialization rules instead of Newtonsoft.Json by setting SerializerSettings to null and providing SerializerOptions. ```csharp var settings = new JsonSchemaGeneratorSettings(); settings.SerializerSettings = null; // Disable Newtonsoft.Json settings.SerializerOptions = new System.Text.Json.JsonSerializerOptions(); // Provide System.Text.Json options var generator = new JsonSchemaGenerator(settings); var schema = generator.Generate(typeof(Person)); ``` -------------------------------- ### TypeScript Class: Test Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.TypeScript.Tests/Snapshots/ExtensionCodeTests.When_classes_have_extension_code_then_class_body_is_copied.verified.txt A simple TypeScript class named 'Test' with an empty 'doIt' method. This serves as a basic example of a class definition. ```typescript export class Test { doIt() { } } ``` -------------------------------- ### Create Plan Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.Tests/Deserialization/Snapshots/DeserializationTests.CanRoundTripPayPalOpenApi.verified.txt Creates a billing plan with specified pricing and billing cycle details for PayPal subscriptions. This allows for defining recurring payment structures. ```APIDOC ## POST /v1/billing/plans ### Description Creates a plan that defines pricing and billing cycle details for subscriptions. ### Method POST ### Endpoint /v1/billing/plans ### Request Body - **product_id** (string) - Required - The ID of the product for which the plan is created. - **name** (string) - Required - The name of the plan. - **description** (string) - Optional - A description of the plan. - **status** (string) - Optional - The status of the plan (e.g., ACTIVE). - **billing_cycles** (array) - Required - An array of billing cycle definitions. - **frequency** (object) - Required - Defines the frequency of the billing cycle. - **interval_unit** (string) - Required - The unit of time for the interval (e.g., MONTH, YEAR). - **interval_count** (integer) - Required - The number of interval units. - **tenure_type** (string) - Required - The type of tenure (e.g., TRIAL, REGULAR). - **sequence** (integer) - Required - The sequence number of the billing cycle. - **total_cycles** (integer) - Optional - The total number of cycles for this billing cycle. - **pricing_scheme** (object) - Required - Defines the pricing for the billing cycle. - **fixed_price** (object) - Required - The fixed price for the billing cycle. - **value** (string) - Required - The price value. - **currency_code** (string) - Required - The currency code (e.g., USD). - **version** (integer) - Optional - The version of the pricing scheme. - **create_time** (string) - Optional - The creation timestamp. - **update_time** (string) - Optional - The update timestamp. - **payment_preferences** (object) - Optional - Payment preferences for the plan. - **auto_bill_outstanding** (boolean) - Optional - Whether to automatically bill outstanding amounts. ### Request Example ```json { "product_id": "PROD-XXCD1234QWER65782", "name": "Video Streaming Service Plan", "description": "Video Streaming Service basic plan", "status": "ACTIVE", "billing_cycles": [ { "frequency": { "interval_unit": "MONTH", "interval_count": 1 }, "tenure_type": "TRIAL", "sequence": 1, "total_cycles": 2, "pricing_scheme": { "fixed_price": { "value": "3", "currency_code": "USD" } } }, { "frequency": { "interval_unit": "MONTH", "interval_count": 1 }, "tenure_type": "REGULAR", "sequence": 2, "total_cycles": 12, "pricing_scheme": { "fixed_price": { "currency_code": "USD", "value": "10" } } } ], "payment_preferences": { "auto_bill_outstanding": true } } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created plan. - **product_id** (string) - The ID of the product associated with the plan. - **name** (string) - The name of the plan. - **description** (string) - The description of the plan. - **status** (string) - The current status of the plan. - **billing_cycles** (array) - An array of billing cycle definitions. - **create_time** (string) - The timestamp when the plan was created. - **update_time** (string) - The timestamp when the plan was last updated. #### Response Example ```json { "id": "P-5ML4271244454362WXNWU5NQ", "product_id": "PROD-XXCD1234QWER65782", "name": "Video Streaming Service Plan", "description": "Video Streaming Service basic plan", "status": "ACTIVE", "billing_cycles": [ { "frequency": { "interval_unit": "MONTH", "interval_count": 1 }, "tenure_type": "TRIAL", "sequence": 1, "total_cycles": 2, "pricing_scheme": { "fixed_price": { "value": "3", "currency_code": "USD" }, "version": 1, "create_time": "2020-05-27T12:13:51Z", "update_time": "2020-05-27T12:13:51Z" } }, { "frequency": { "interval_unit": "MONTH", "interval_count": 1 }, "tenure_type": "TRIAL", "sequence": 2, "total_cycles": 3, "pricing_scheme": { "fixed_price": { "currency_code": "USD", "value": "6" }, "version": 1, "create_time": "2020-05-27T12:13:51Z", "update_time": "2020-05-27T12:13:51Z" } }, { "frequency": { "interval_unit": "MONTH", "interval_count": 1 }, "tenure_type": "REGULAR", "sequence": 3, "total_cycles": 12, "pricing_scheme": { "fixed_price": { "currency_code": "USD", "value": "10" }, "version": 1, "create_time": "2020-05-27T12:13:51Z", "update_time": "2020-05-27T12:13:51Z" } } ], "payment_preferences": { "auto_bill_outstanding": true } } ``` ``` -------------------------------- ### Get Object Subtype Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/InheritanceTests.When_class_with_discriminator_has_base_class_then_csharp_is_generated_correctly.verified.txt Retrieves the specific subtype of an object based on a discriminator value. It iterates through custom attributes to find a matching JsonInheritanceAttribute. ```csharp private System.Type GetObjectSubtype(System.Type objectType, string discriminator) { foreach (var attribute in System.Reflection.CustomAttributeExtensions.GetCustomAttributes(System.Reflection.IntrospectionExtensions.GetTypeInfo(objectType), true)) { if (attribute.Key == discriminator) return attribute.Type; } return objectType; } ``` -------------------------------- ### Enable XML Documentation File Generation Source: https://github.com/ricosuter/njsonschema/wiki/XML-Documentation To generate an XML documentation file for your .NET project, add this element to your project file. This file is used by njsonschema to populate schema attributes. ```xml true ``` -------------------------------- ### SubClass2 Initialization and Serialization Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.Tests/Snapshots/InheritanceSerializationTests.When_schema_contains_discriminator_and_inheritance_hierarchy_then_TypeScript_is_correctly_generated.verified.txt Handles initialization from data and serialization for SubClass2, including its specific property. ```TypeScript override toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["Prop2"] = this.prop2; super.toJSON(data); return data; } } export interface ISubClass2 extends ISubClass { prop2: string | undefined; } ``` -------------------------------- ### Get Subtype Discriminator Key Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/InheritanceInterfaceTests.When_schema_has_base_schema_then_it_is_referenced_with_STJ.verified.txt Determines the discriminator key associated with a specific object type based on JsonInheritanceAttribute. Returns null if the attribute is not found. ```csharp private string GetSubtypeDiscriminator(System.Type objectType) { foreach (var attribute in System.Reflection.CustomAttributeExtensions.GetCustomAttributes(System.Reflection.IntrospectionExtensions.GetTypeInfo(objectType), true)) { if (attribute.Type == objectType) return attribute.Key; } return null; } ``` -------------------------------- ### Get Discriminator Key for Inherited Type Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/InheritanceInterfaceTests.When_schema_has_base_schema_then_it_is_referenced_with_Newtonsoft.verified.txt Retrieves the discriminator key for a given object type based on JsonInheritanceAttribute. Useful when defining polymorphic serialization. ```csharp private string GetSubtypeDiscriminator(System.Type objectType) { foreach (var attribute in System.Reflection.CustomAttributeExtensions.GetCustomAttributes(System.Reflection.IntrospectionExtensions.GetTypeInfo(objectType), true)) { if (attribute.Type == objectType) return attribute.Key; } return objectType.Name; } ``` -------------------------------- ### Load JSON Schema from File Source: https://context7.com/ricosuter/njsonschema/llms.txt Read a schema file from disk using JsonSchema.FromFileAsync(). Relative $ref paths in the schema will be resolved relative to the file's location. ```csharp using NJsonSchema; var schema = await JsonSchema.FromFileAsync("/path/to/schema.json"); Console.WriteLine(schema.Title); ``` -------------------------------- ### Get Object Subtype by Discriminator Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/InheritanceInterfaceTests.When_schema_has_base_schema_then_it_is_referenced_with_STJ.verified.txt Finds the specific subtype associated with a given discriminator value from a base type. Returns null if no matching attribute is found. ```csharp private System.Type GetObjectSubtype(System.Type baseType, string discriminatorValue) { foreach (var attribute in System.Reflection.CustomAttributeExtensions.GetCustomAttributes(System.Reflection.IntrospectionExtensions.GetTypeInfo(baseType), true)) { if (attribute.Key == discriminatorValue) return attribute.Type; } return null; } ``` -------------------------------- ### Get Subtype Discriminator Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/InheritanceTests.When_class_with_discriminator_has_base_class_then_csharp_is_generated_correctly.verified.txt Determines the discriminator key for a given object type by examining its custom attributes. Returns the type name if no specific discriminator is found. ```csharp private string GetSubtypeDiscriminator(System.Type objectType) { foreach (var attribute in System.Reflection.CustomAttributeExtensions.GetCustomAttributes(System.Reflection.IntrospectionExtensions.GetTypeInfo(objectType), true)) { if (attribute.Type == objectType) return attribute.Key; } return objectType.Name; } } } ``` -------------------------------- ### StringLengthAttribute Example in C# Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/GeneralGeneratorTests.When_definition_contains_both_min_and_max_length_a_string_length_attribute_is_added.verified.txt This C# code demonstrates the use of StringLengthAttribute to enforce both minimum and maximum length constraints on a string property. Ensure the System.ComponentModel.DataAnnotations namespace is imported. ```csharp //---------------------- // // //---------------------- namespace MyNamespace { #pragma warning disable // Disable all warnings public partial class MyClass { [Newtonsoft.Json.JsonProperty("foo", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] [System.ComponentModel.DataAnnotations.StringLength(20, MinimumLength = 10)] public string Foo { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary AdditionalProperties { get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } set { _additionalProperties = value; } } } } ``` -------------------------------- ### Generate JSON Schema from Sample JSON Source: https://github.com/ricosuter/njsonschema/blob/master/README.md Use this to generate a JSON Schema based on the default JSON Schema specification. Provide sample JSON data as a string. ```csharp var generator = new SampleJsonSchemaGenerator(new SampleJsonSchemaGeneratorSettings()); var schema = generator.Generate("{...}"); ``` ```json { "int": 1, "float": 340282346638528859811704183484516925440.0, "str": "abc", "bool": true, "date": "2012-07-19", "datetime": "2012-07-19 10:11:11", "timespan": "10:11:11" } ``` ```json { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "int": { "type": "integer" }, "float": { "type": "number" }, "str": { "type": "string" }, "bool": { "type": "boolean" }, "date": { "type": "string", "format": "date" }, "datetime": { "type": "string", "format": "date-time" }, "timespan": { "type": "string", "format": "duration" } } } ``` -------------------------------- ### Generate Schema from Sample JSON Source: https://github.com/ricosuter/njsonschema/wiki/SampleJsonSchemaGenerator Use the static `FromJsonSample` method to quickly generate a JSON Schema from a sample JSON string. The resulting schema can then be converted to its JSON representation. ```csharp var schema = JsonSchema.FromSampleJson("..."); var schemaJson = schema.ToJson(); ``` -------------------------------- ### Custom Format Validators for JsonSchemaValidator Source: https://context7.com/ricosuter/njsonschema/llms.txt Extend JsonSchemaValidator with custom IFormatValidator implementations to support additional string formats. The SsnFormatValidator example checks for a specific Social Security Number pattern. ```csharp using NJsonSchema; using NJsonSchema.Validation; using NJsonSchema.Validation.FormatValidators; public class SsnFormatValidator : IFormatValidator { public string Format => "ssn"; public ValidationErrorKind ValidationErrorKind => ValidationErrorKind.StringFormatMismatch; public bool IsValid(string value, JToken token) => System.Text.RegularExpressions.Regex.IsMatch(value, @"^\d{3}-\d{2}-\d{4}$"); } var schema = await JsonSchema.FromJsonAsync(""" { \"type\": \"object\", \"properties\": { \"ssn\": { \"type\": \"string\", \"format\": \"ssn\" } } }""" ); var validator = new JsonSchemaValidator(new SsnFormatValidator()); var errors = validator.Validate("{ \"ssn\": \"invalid\" }", schema); Console.WriteLine(errors.Count); // 1 ``` -------------------------------- ### C# PostAddress Class with Inheritance Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/GeneralGeneratorTests.When_record_has_inheritance.verified.txt Defines a `PostAddress` class that inherits from `AbstractAddress`. It includes a JSON constructor and properties for `Zip` and `HouseNumber`, with specific JSON serialization requirements. ```csharp //---------------------- // // //---------------------- namespace MyNamespace { #pragma warning disable // Disable all warnings public partial class PostAddress : AbstractAddress { [Newtonsoft.Json.JsonConstructor] public PostAddress(string @city, int @houseNumber, string @streetName, string @zip) : base(city, streetName) { this.Zip = @zip; this.HouseNumber = @houseNumber; } [Newtonsoft.Json.JsonProperty("Zip", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Zip { get; } [Newtonsoft.Json.JsonProperty("HouseNumber", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public int HouseNumber { get; } } public abstract partial class AbstractAddress { [Newtonsoft.Json.JsonConstructor] protected AbstractAddress(string @city, string @streetName) { this.City = @city; this.StreetName = @streetName; } [Newtonsoft.Json.JsonProperty("city", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string City { get; } [Newtonsoft.Json.JsonProperty("streetName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string StreetName { get; } } public partial class PersonAddress : PostAddress { [Newtonsoft.Json.JsonConstructor] public PersonAddress(string @addressee, string @city, int @houseNumber, string @streetName, string @zip) : base(city, houseNumber, streetName, zip) { this.Addressee = @addressee; } [Newtonsoft.Json.JsonProperty("Addressee", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Addressee { get; } } } ``` -------------------------------- ### C# Person Class Definition Source: https://github.com/ricosuter/njsonschema/blob/master/README.md Defines a `Person` class with various properties including required fields, enums, ranges, dates, and nested objects/collections. This class is used as an example for JSON schema generation. ```csharp public class Person { [Required] public string FirstName { get; set; } public string MiddleName { get; set; } [Required] public string LastName { get; set; } public Gender Gender { get; set; } [Range(2, 5)] public int NumberWithRange { get; set; } public DateTime Birthday { get; set; } public Company Company { get; set; } public Collection Cars { get; set; } } public enum Gender { Male, Female } public class Car { public string Name { get; set; } public Company Manufacturer { get; set; } } public class Company { public string Name { get; set; } } ``` -------------------------------- ### Inherit Schema from allOf Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/AllOfTests.When_allOf_has_one_schema_then_it_is_inherited.verified.txt Demonstrates how a schema defined within an allOf construct is inherited when it contains only one schema. ```csharp using System.Threading.Tasks; using NJsonSchema.CodeGeneration.CSharp; using Xunit; namespace NJsonSchema.CodeGeneration.Tests.CodeGeneration { public class AllOfTests { [Fact] public async Task When_allOf_has_one_schema_then_it_is_inherited() { // Arrange var schema = Schema.FromJson(@"{ ""allOf"": [ { ""type"": ""object"", ""properties"": { ""foo"": {""type"": ""string""} } } ] }"); // Act var codeGenerator = new CSharpGenerator(schema); var code = codeGenerator.GenerateFile("MyClass"); // Assert Assert.Contains("public string Foo { get; set; }", code); } } } ``` -------------------------------- ### Custom Type and Format for Class with JsonSchemaAttribute Source: https://github.com/ricosuter/njsonschema/wiki/JsonSchemaGenerator Use JsonSchemaAttribute to override the default type and format for a C# class in the generated JSON Schema. This example sets a 'Point' class to be a 'string' with a 'point' format. ```csharp public class Point { public decimal X { get; set; } public decimal Y { get; set; } } public class AnnotationClass { public Point Point { get; set; } } ``` ```csharp [JsonSchema(JsonObjectType.String, Format = "point")] public class Point { public decimal X { get; set; } public decimal Y { get; set; } } public class AnnotationClass { public Point Point { get; set; } } ``` -------------------------------- ### SubClass3 Initialization and Serialization Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.Tests/Snapshots/InheritanceSerializationTests.When_schema_contains_discriminator_and_inheritance_hierarchy_then_TypeScript_is_correctly_generated.verified.txt Implements initialization and serialization for SubClass3, extending SubClass2 and adding its own property. ```TypeScript export class SubClass3 extends SubClass2 implements ISubClass3 { prop3!: string | undefined; constructor(data?: ISubClass3) { super(data); this._discriminator = "SubClass3"; } override init(_data?: any) { super.init(_data); if (_data) { this.prop3 = _data["Prop3"]; } } static override fromJS(data: any): SubClass3 { data = typeof data === 'object' ? data : {}; let result = new SubClass3(); result.init(data); return result; } override toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["Prop3"] = this.prop3; super.toJSON(data); return data; } } export interface ISubClass3 extends ISubClass2 { prop3: string | undefined; } ``` -------------------------------- ### TypeScript Class: MyItem Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.TypeScript.Tests/Snapshots/TypeScriptDictionaryTests.When_dictionary_value_is_object_then_typescript_has_any_value.verified.txt Represents an item with an optional extensions dictionary. The constructor and init methods handle data initialization, and fromJS/toJSON provide serialization/deserialization capabilities. ```typescript export class MyItem implements IMyItem { readonly extensions!: { [key: string]: any; } | undefined; constructor(data?: IMyItem) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (this as any)[property] = (data as any)[property]; } } } init(_data?: any) { if (_data) { if (_data["extensions"]) { (this as any).extensions = {} as any; for (let key in _data["extensions"]) { if (_data["extensions"].hasOwnProperty(key)) ((this as any).extensions as any)![key] = _data["extensions"][key]; } } } } static fromJS(data: any): MyItem { data = typeof data === 'object' ? data : {}; let result = new MyItem(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; if (this.extensions) { data["extensions"] = {}; for (let key in this.extensions) { if (this.extensions.hasOwnProperty(key)) (data["extensions"] as any)[key] = (this.extensions as any)[key]; } } return data; } } ``` -------------------------------- ### Generate and Validate JSON Schema Source: https://github.com/ricosuter/njsonschema/wiki/JsonSchema Demonstrates generating a JSON schema from a C# type, serializing it, validating a JSON string against it, and deserializing a schema from JSON. Prefer Validate(string) for accurate date/time handling. ```cs var schema = JsonSchema.FromType(); var schemaData = schema.ToJson(); var jsonData = "{...}"; var errors = schema.Validate(jsonData); foreach (var error in errors) Console.WriteLine(error.Path + ": " + error.Kind); schema = await JsonSchema.FromJsonAsync(schemaData); ``` -------------------------------- ### Get Discriminator Key from Type (C#) Source: https://github.com/ricosuter/njsonschema/blob/master/src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/InheritanceTests.When_definitions_inherit_from_root_schema.verified.txt Retrieves the discriminator key associated with a specific type from custom JSON inheritance attributes. This is used to find the key that identifies a particular derived schema within a base schema. ```csharp foreach (var attribute in System.Reflection.CustomAttributeExtensions.GetCustomAttributes(System.Reflection.IntrospectionExtensions.GetTypeInfo(objectType), true)) { if (attribute.Type == objectType) return attribute.Key; } return objectType.Name; } } } ```