feat(JSON to C#): update to add options from json2csharp.com

rootTypeName (choose root object name)
pascalCase (type and member names)
useFields (instead of properties)
useNullable (types)
addJsonProperty (Newtonsoft) and nullValueHandlingIgnore
addJsonPropertyName (System.Text.Json)
generateImmutableClasses
useRecordTypes
useReadonlyLists
This commit is contained in:
ShareVB committed 2025-03-08 21:56:26 +01:00
1 parent b956e9f718
commit 62e2e30f90
5 files changed
+908 -28

No files matched your search

-1
View File
@@ -156,7 +156,6 @@
"json-analyzer": "^1.2.2",
"json-editor-vue": "^0.16.0",
"json-to-ts": "^1.7.0",
"json2csharp": "^1.0.3",
"json5": "^2.2.3",
"jsonar-mod": "^1.9.0",
"jsonlint-mod": "^1.7.6",
+76 -24
View File
@@ -1,9 +1,10 @@
<script setup lang="ts">
import JSON5 from 'json5';
import json2csharp from 'json2csharp';
import json2csharp from './json2csharp';
import type { UseValidationRule } from '@/composable/validation';
import TextareaCopyable from '@/components/TextareaCopyable.vue';
import { withDefaultOnError } from '@/utils/defaults';
import { useQueryParamOrStorage } from '@/composable/queryParams';
const defaultValue = `{
a:"n",
@@ -14,9 +15,31 @@ const defaultValue = `{
}
}`;
const jsonInput = ref(defaultValue);
const useNewtonsoft = useStorage('json-to-csharp:newtonsoft', false);
const pascalCase = useQueryParamOrStorage({ name: 'pascalcase', storageName: 'json-c#:pc', defaultValue: true });
const useFields = useQueryParamOrStorage({ name: 'fields', storageName: 'json-c#:fi', defaultValue: false });
const useNullable = useQueryParamOrStorage({ name: 'nullable', storageName: 'json-c#:null', defaultValue: false });
const addJsonProperty = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:jsp', defaultValue: false });
const nullValueHandlingIgnore = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:ign', defaultValue: true });
const addJsonPropertyName = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:jspp', defaultValue: true });
const generateImmutableClasses = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:imm', defaultValue: false });
const useRecordTypes = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:rec', defaultValue: true });
const useReadonlyLists = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:rdl', defaultValue: false });
const rootTypeName = useQueryParamOrStorage({ name: 'root', storageName: 'json-c#:rt', defaultValue: 'Root' });
const csharpOutput = computed(() => withDefaultOnError(
() => json2csharp(JSON.stringify(JSON5.parse(jsonInput.value)), useNewtonsoft.value), ''));
() => json2csharp({
src: JSON5.parse(jsonInput.value),
rootTypeName: rootTypeName.value,
pascalCase: pascalCase.value,
useFields: useFields.value,
useNullable: useNullable.value,
addJsonProperty: addJsonProperty.value,
nullValueHandlingIgnore: nullValueHandlingIgnore.value,
addJsonPropertyName: addJsonPropertyName.value,
generateImmutableClasses: generateImmutableClasses.value,
useRecordTypes: useRecordTypes.value,
useReadonlyLists: useReadonlyLists.value,
}), ''));
const rules: UseValidationRule<string>[] = [
{
validator: (v: string) => v === '' || JSON5.parse(v),
@@ -26,25 +49,54 @@ const rules: UseValidationRule<string>[] = [
</script>
<template>
<c-card title="JSON to C#">
<c-input-text
v-model:value="jsonInput"
multiline
placeholder="Put your json string here..."
rows="20"
label="JSON to C#"
:validation-rules="rules"
raw-text
mb-5
/>
<n-checkbox v-model:checked="useNewtonsoft">
<span title="Use Newtonsoft Annotations">Use Newtonsoft Annotations</span>
</n-checkbox>
</c-card>
<c-card title="Your C# code">
<TextareaCopyable
:value="csharpOutput"
language="csharp"
/>
</c-card>
<div>
<c-card title="JSON to C#">
<c-input-text
v-model:value="jsonInput"
multiline
placeholder="Put your json string here..."
rows="10"
label="JSON to C#"
:validation-rules="rules"
raw-text
mb-5
/>
<n-space justify="center">
<n-checkbox v-model:checked="pascalCase">
Use Pascal case
</n-checkbox>
<n-checkbox v-model:checked="useRecordTypes">
Use Record types
</n-checkbox>
<n-checkbox v-model:checked="generateImmutableClasses">
Generate Immutable classes
</n-checkbox>
<n-checkbox v-model:checked="useFields">
Use fields
</n-checkbox>
<n-checkbox v-model:checked="addJsonProperty">
Add JsonProperty attributes
</n-checkbox>
<n-checkbox v-model:checked="nullValueHandlingIgnore" :disabled="!addJsonProperty">
Use NullValueHandling.Ignore
</n-checkbox>
<n-checkbox v-model:checked="addJsonPropertyName">
Add JsonPropertyName attributes
</n-checkbox>
<n-checkbox v-model:checked="useNullable">
Use nullable types
</n-checkbox>
<n-checkbox v-model:checked="useReadonlyLists">
Use Readonly lists
</n-checkbox>
</n-space>
<c-input-text v-model:value="rootTypeName" label="Root type name" placeholder="Your root type name..." clearable raw-text mb-5 />
</c-card>
<c-card title="Your C# code" mt-2>
<TextareaCopyable
:value="csharpOutput"
language="csharp"
/>
</c-card>
</div>
</template>
-3
View File
@@ -1,3 +0,0 @@
declare module 'json2csharp'{
export default function(json: string, useNewtonsoftAnnotations?: boolean): string;
}
@@ -0,0 +1,617 @@
import { describe, expect, it } from 'vitest';
import { getPrimitiveProp, isDate, json2classes, json2csharp } from './json2csharp';
// Test isDate function
describe('isDate', () => {
it('should return true for valid date strings', () => {
expect(isDate('2024-03-08')).toBe(true);
expect(isDate('2024-03-08T12:34:56Z')).toBe(true);
});
it('should return false for invalid date strings', () => {
expect(isDate('hello')).toBe(false);
expect(isDate('2024-13-08')).toBe(false); // Invalid month
expect(isDate('9999-99-99')).toBe(false); // Invalid format
});
});
// Test getPrimitiveProp function
describe('getPrimitiveProp', () => {
it('should return \'string\' type for non-date strings', () => {
expect(getPrimitiveProp('hello', 'testKey')).toEqual({
type: 'string',
name: 'testKey',
canBeNullable: false,
});
});
it('should return \'DateTime\' type for date strings', () => {
expect(getPrimitiveProp('2024-03-08', 'dateKey')).toEqual({
type: 'DateTime',
name: 'dateKey',
canBeNullable: true,
});
});
it('should return \'int\' for integers', () => {
expect(getPrimitiveProp(42, 'numberKey')).toEqual({
type: 'int',
name: 'numberKey',
canBeNullable: true,
});
});
it('should return \'double\' for floating point numbers', () => {
expect(getPrimitiveProp(3.14, 'floatKey')).toEqual({
type: 'double',
name: 'floatKey',
canBeNullable: true,
});
});
it('should return \'bool\' for boolean values', () => {
expect(getPrimitiveProp(true, 'boolKey')).toEqual({
type: 'bool',
name: 'boolKey',
canBeNullable: true,
});
});
it('should throw an error for unsupported types', () => {
expect(() => getPrimitiveProp({}, 'objKey')).toThrow('Unexpected key \'objKey\' of type object');
});
});
// Test json2classes function
describe('json2classes', () => {
it('should convert JSON to class definitions with custom root', () => {
const json = { name: 'John', age: 30 };
const result = json2classes(json, 'Main');
expect(result).to.deep.eq([
{
key: 'Main',
props: [
{ type: 'string', name: 'name', canBeNullable: false },
{ type: 'int', name: 'age', canBeNullable: true },
],
},
]);
});
it('should handle nested objects', () => {
const json = { user: { name: 'John' } };
const result = json2classes(json);
expect(result).to.deep.eq([
{ key: 'Root', props: [{ type: 'User', name: 'user' }] },
{ key: 'User', props: [{ type: 'string', name: 'name', canBeNullable: false }] },
]);
});
it('should handle arrays of primitives', () => {
const json = { numbers: [1, 2, 3] };
const result = json2classes(json);
expect(result).to.deep.eq([
{ key: 'Root', props: [{ type: 'int', name: 'numbers', isArray: true, canBeNullable: true }] },
]);
});
it('should handle arrays of objects', () => {
const json = { users: [{ name: 'John' }, { name: 'Jane' }] };
const result = json2classes(json);
expect(result).to.deep.eq([
{ key: 'Root', props: [{ type: 'UsersItem', name: 'users', isArray: true }] },
{ key: 'UsersItem', props: [{ type: 'string', name: 'name', canBeNullable: false }] },
]);
});
});
// Test json2csharp function
describe('json2csharp', () => {
const cleanTabs = (s: string) => s.replace(/\t/g, ' ');
it('should convert JSON to C# class with default options', () => {
const json = JSON.stringify({ name: 'John', age: 30 });
const result = cleanTabs(json2csharp({ src: json }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"name\")]
public string Name { get; set; }
[JsonPropertyName(\"age\")]
public int Age { get; set; }
}`);
});
it('should not change case if pascalCase option is false', () => {
const json = JSON.stringify({ test: { user_name: 'John' } });
const result = cleanTabs(json2csharp({ src: json, pascalCase: false }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"test\")]
public Test test { get; set; }
}
public class Test
{
[JsonPropertyName(\"user_name\")]
public string user_name { get; set; }
}`);
});
it('should handle when root is an array', () => {
const json = JSON.stringify([{ age: 30 }]);
const result = cleanTabs(json2csharp({ src: json, useNullable: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class RootItem
{
[JsonPropertyName(\"age\")]
public int? Age { get; set; }
}`);
});
it('should use nullable types if useNullable option is true', () => {
const json = JSON.stringify({ age: 30 });
const result = cleanTabs(json2csharp({ src: json, useNullable: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"age\")]
public int? Age { get; set; }
}`);
});
it('should add JsonProperty attributes if addJsonProperty is true', () => {
const json = JSON.stringify({ name: 'John' });
const result = cleanTabs(json2csharp({ src: json, addJsonProperty: true }));
expect(result).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public class Root
{
[JsonProperty(\"name\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"name\")]
public string Name { get; set; }
}`);
});
it('should add JsonPropertyName attributes if addJsonPropertyName is true', () => {
const json = JSON.stringify({ name: 'John' });
const result = cleanTabs(json2csharp({ src: json, addJsonPropertyName: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"name\")]
public string Name { get; set; }
}`);
});
it('should generate immutable classes if generateImmutableClasses is true', () => {
const json = JSON.stringify({ name: 'John' });
const result = cleanTabs(json2csharp({ src: json, generateImmutableClasses: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
public Root(
string name
){
this.Name = name;
}
[JsonPropertyName(\"name\")]
public string Name { get; }
}`);
});
it('should convert JSON with arrays into C# classes', () => {
const json = {
users: [{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }],
};
expect(cleanTabs(json2csharp({ src: json }))).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"users\")]
public UsersItem[] Users { get; set; }
}
public class UsersItem
{
[JsonPropertyName(\"name\")]
public string Name { get; set; }
[JsonPropertyName(\"age\")]
public int Age { get; set; }
}`);
expect(cleanTabs(json2csharp({ src: json, useRecordTypes: true }))).toBe(`using System;
using System.Text.Json;
public record Root(
[property: JsonPropertyName(\"users\")]
UsersItem[] Users
);
public record UsersItem(
[property: JsonPropertyName(\"name\")]
string Name,
[property: JsonPropertyName(\"age\")]
int Age
);`);
expect(cleanTabs(json2csharp({ src: json, useRecordTypes: true, pascalCase: false, useReadonlyLists: true }))).toBe(`using System;
using System.Text.Json;
public record Root(
[property: JsonPropertyName(\"users\")]
IReadonlyList<UsersItem> users
);
public record UsersItem(
[property: JsonPropertyName(\"name\")]
string name,
[property: JsonPropertyName(\"age\")]
int age
);`);
});
it('should generate C# record types when useRecordTypes is true', () => {
const json = JSON.stringify({ name: 'John', age: 30 });
const result = cleanTabs(json2csharp({ src: json, useRecordTypes: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public record Root(
[property: JsonPropertyName(\"name\")]
string Name,
[property: JsonPropertyName(\"age\")]
int Age
);`);
});
it('should generate C# record types with attributes when useRecordTypes/addJsonProperty/addJsonPropertyName are true', () => {
const json = JSON.stringify({ name: 'John', age: 30 });
const result = cleanTabs(json2csharp({
src: json,
useRecordTypes: true,
addJsonProperty: true,
addJsonPropertyName: true,
}));
expect(result).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public record Root(
[property: JsonProperty(\"name\", NullValueHandling = NullValueHandling.Ignore)]
[property: JsonPropertyName(\"name\")]
string Name,
[property: JsonProperty(\"age\", NullValueHandling = NullValueHandling.Ignore)]
[property: JsonPropertyName(\"age\")]
int Age
);`);
});
it('should handle arrays of primitives', () => {
const json = JSON.stringify({ numbers: [1, 2, 3] });
const result = cleanTabs(json2csharp({ src: json }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"numbers\")]
public int[] Numbers { get; set; }
}`);
});
it('should handle arrays of objects with PascalCase enabled', () => {
const json = JSON.stringify({
items: [{ item_name: 'A', price: 10.5 }],
});
const result = cleanTabs(json2csharp({
src: json,
pascalCase: true,
addJsonProperty: true,
addJsonPropertyName: true,
}));
expect(result).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public class Root
{
[JsonProperty(\"items\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"items\")]
public ItemsItem[] Items { get; set; }
}
public class ItemsItem
{
[JsonProperty(\"item_name\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"item_name\")]
public string ItemName { get; set; }
[JsonProperty(\"price\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"price\")]
public double Price { get; set; }
}`);
});
it('should use nullable types for optional fields when useNullable is true', () => {
const json = JSON.stringify({ age: null, price: 10.5 });
const result = cleanTabs(json2csharp({ src: json, useNullable: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"age\")]
public Age Age { get; set; }
[JsonPropertyName(\"price\")]
public double? Price { get; set; }
}
public class Age
{
}`);
});
it('should use fields when useFields is true', () => {
const json = JSON.stringify({ age: 1, price: 10.5 });
const result = cleanTabs(json2csharp({ src: json, useFields: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"age\")]
public int Age;
[JsonPropertyName(\"price\")]
public double Price;
}`);
});
it('should add JsonProperty attributes when addJsonProperty is true', () => {
const json = JSON.stringify({ firstName: 'John', lastName: 'Doe' });
const result = cleanTabs(json2csharp({ src: json, addJsonProperty: true, nullValueHandlingIgnore: false }));
expect(result).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public class Root
{
[JsonProperty(\"firstName\")]
[JsonPropertyName(\"firstName\")]
public string FirstName { get; set; }
[JsonProperty(\"lastName\")]
[JsonPropertyName(\"lastName\")]
public string LastName { get; set; }
}`);
});
it('should add JsonProperty attributes when addJsonProperty and nullValueHandlingIgnore are true', () => {
const json = JSON.stringify({ firstName: 'John', lastName: 'Doe' });
const result = cleanTabs(json2csharp({ src: json, addJsonProperty: true, nullValueHandlingIgnore: true }));
expect(result).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public class Root
{
[JsonProperty(\"firstName\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"firstName\")]
public string FirstName { get; set; }
[JsonProperty(\"lastName\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"lastName\")]
public string LastName { get; set; }
}`);
});
it('should handle all types', () => {
const json = JSON.stringify({
id: 1, date: '2025-06-09', amount: 1.4, group: null, active: true, email: 'test@example.com',
});
const result = cleanTabs(json2csharp({ src: json }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"id\")]
public int Id { get; set; }
[JsonPropertyName(\"date\")]
public DateTime Date { get; set; }
[JsonPropertyName(\"amount\")]
public double Amount { get; set; }
[JsonPropertyName(\"group\")]
public Group Group { get; set; }
[JsonPropertyName(\"active\")]
public bool Active { get; set; }
[JsonPropertyName(\"email\")]
public string Email { get; set; }
}
public class Group
{
}`);
});
it('should use readonly lists when useReadonlyLists is true', () => {
const json = JSON.stringify({
items: [{ name: 'Item1' }, { name: 'Item2' }],
});
const result = cleanTabs(json2csharp({ src: json, useReadonlyLists: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
[JsonPropertyName(\"items\")]
public List<ItemsItem> Items { get; } = new List<ItemsItem>;
}
public class ItemsItem
{
[JsonPropertyName(\"name\")]
public string Name { get; set; }
}`);
});
it('should use immutable class properties when generateImmutableClasses is true', () => {
const json = JSON.stringify({ title: 'Book', pages: 300 });
const result = cleanTabs(json2csharp({ src: json, generateImmutableClasses: true }));
expect(result).toBe(`using System;
using System.Text.Json;
public class Root
{
public Root(
string title,
int pages
){
this.Title = title;
this.Pages = pages;
}
[JsonPropertyName(\"title\")]
public string Title { get; }
[JsonPropertyName(\"pages\")]
public int Pages { get; }
}`);
});
it('should generate a combination of options correctly', () => {
const json = JSON.stringify({
people: [
{ first_name: 'John', age: 30 },
{ first_name: 'Jane', age: 25 },
],
});
expect(cleanTabs(json2csharp({
src: json,
pascalCase: true,
useNullable: true,
addJsonProperty: true,
generateImmutableClasses: true,
useRecordTypes: false,
useReadonlyLists: true,
}))).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public class Root
{
public Root(
List<PeopleItem> people
){
this.People = people;
}
[JsonProperty(\"people\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"people\")]
public List<PeopleItem> People { get; } = new List<PeopleItem>;
}
public class PeopleItem
{
public PeopleItem(
string firstName,
int? age
){
this.FirstName = firstName;
this.Age = age;
}
[JsonProperty(\"first_name\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"first_name\")]
public string FirstName { get; }
[JsonProperty(\"age\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"age\")]
public int? Age { get; }
}`);
expect(cleanTabs(json2csharp({
src: json,
pascalCase: true,
useNullable: true,
addJsonProperty: true,
addJsonPropertyName: true,
generateImmutableClasses: false,
useRecordTypes: false,
useReadonlyLists: true,
}))).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public class Root
{
[JsonProperty(\"people\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"people\")]
public List<PeopleItem> People { get; } = new List<PeopleItem>;
}
public class PeopleItem
{
[JsonProperty(\"first_name\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"first_name\")]
public string FirstName { get; set; }
[JsonProperty(\"age\", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName(\"age\")]
public int? Age { get; set; }
}`);
expect(cleanTabs(json2csharp({
src: json,
pascalCase: true,
useNullable: true,
addJsonProperty: true,
useRecordTypes: true,
useReadonlyLists: true,
}))).toBe(`using System;
using Newtonsoft.Json;
using System.Text.Json;
public record Root(
[property: JsonProperty(\"people\", NullValueHandling = NullValueHandling.Ignore)]
[property: JsonPropertyName(\"people\")]
IReadonlyList<PeopleItem> People
);
public record PeopleItem(
[property: JsonProperty(\"first_name\", NullValueHandling = NullValueHandling.Ignore)]
[property: JsonPropertyName(\"first_name\")]
string FirstName,
[property: JsonProperty(\"age\", NullValueHandling = NullValueHandling.Ignore)]
[property: JsonPropertyName(\"age\")]
int? Age
);`);
});
});
+215
View File
@@ -0,0 +1,215 @@
import { camelCase as convertToCamelCase, pascalCase as convertToPascalCase } from 'change-case';
import JSON5 from 'json5';
function normalize(src: string, firstUpper = true) {
// return /^\d$/.test(src.charAt(0))
// ? `N${pascalCase(src)}`
// : pascalCase(src);
return /^\d$/.test(src.charAt(0))
? `N${src}`
: (firstUpper ? src.charAt(0).toUpperCase() + src.slice(1) : src);
}
export function isDate(src: string) {
return /^(\d{4})(-(0[1-9]|1[0-2])(-([12]\d|0[1-9]|3[01]))([T\s]((([01]\d|2[0-3])((:)[0-5]\d))([\:]\d+)?)?(:[0-5]\d([\.]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)$/.test(
src,
);
}
interface Prop { type: string; name: string; isArray?: boolean; canBeNullable?: boolean }
export function getPrimitiveProp(obj: any, key: string): Prop {
const type = typeof obj;
switch (type) {
case 'string':
// eslint-disable-next-line no-case-declarations
const isObjDate = isDate(obj);
return { type: isObjDate ? 'DateTime' : 'string', name: key, canBeNullable: isObjDate };
case 'number':
return { type: Number.isInteger(obj) ? 'int' : 'double', name: key, canBeNullable: true };
case 'boolean':
return { type: 'bool', name: key, canBeNullable: true };
default:
throw new Error(`Unexpected key '${key}' of type ${type}`);
}
}
interface ClassType { key: string; props: Array<Prop> }
function handleObject(
classes: Array<ClassType>,
obj: any,
key: string,
skip: boolean = false) {
const normalizedKey = normalize(key);
let target: ClassType = classes.find(x => x.key === normalizedKey) as never;
if (!target) {
target = { key: normalizedKey, props: [] };
if (!skip) {
classes.push(target);
}
}
if (obj != null) {
Object.keys(obj).forEach((k) => {
const keyName = Number.isNaN(Number(k)) ? k : `${normalizedKey}Item`;
let prop: Prop | null = null;
if (typeof obj[k] == 'object') {
if (Array.isArray(obj[k])) {
if (Array.from(obj[k]).length > 0) {
if (typeof obj[k][0] == 'object') {
handleObject(classes, obj[k], keyName, true);
prop = {
type: normalize(`${keyName}Item`),
name: keyName,
isArray: true,
};
}
else {
prop = getPrimitiveProp(obj[k][0], keyName);
prop.isArray = true;
}
}
}
else {
handleObject(classes, obj[k], keyName);
prop = { type: normalize(keyName), name: keyName };
}
}
else {
prop = getPrimitiveProp(obj[k], keyName);
}
if (prop && !target.props.some(x => x.name === prop?.name)) {
target.props.push(prop);
}
});
}
}
export function json2classes(src: object, rootTypeName: string = 'Root') {
const classes: Array<ClassType> = [];
handleObject(classes, src, rootTypeName);
return classes;
}
export function json2csharp(
{
src,
rootTypeName = 'Root',
pascalCase = true,
nullValueHandlingIgnore = true,
addJsonPropertyName = true,
useReadonlyLists,
useRecordTypes,
addJsonProperty,
generateImmutableClasses,
useFields,
useNullable,
}: {
src: any
rootTypeName?: string
pascalCase?: boolean
useFields?: boolean
useNullable?: boolean
addJsonProperty?: boolean
nullValueHandlingIgnore?: boolean
addJsonPropertyName?: boolean
generateImmutableClasses?: boolean
useRecordTypes?: boolean
useReadonlyLists?: boolean
}) {
const normalizeCase = (s: string) => {
const normalized = normalize(s, pascalCase);
return pascalCase ? convertToPascalCase(normalized) : normalized;
};
const getPropType = (p: Prop) => {
let type = p.type;
if (p.isArray) {
if (useReadonlyLists) {
type = useRecordTypes ? `IReadonlyList<${type}>` : `List<${type}>`;
}
else {
type = `${type}[]`;
}
}
const nullable = useNullable && p.canBeNullable ? '?' : '';
return { type, nullable };
};
const srcObj = typeof src === 'string' ? JSON5.parse(src) : src;
const classes = json2classes(
Array.isArray(srcObj) ? srcObj[0] : srcObj,
Array.isArray(srcObj) ? `${rootTypeName}Item` : rootTypeName);
let result = '';
result += 'using System;\n';
result += addJsonProperty ? 'using Newtonsoft.Json;\n' : '';
result += addJsonPropertyName ? 'using System.Text.Json;\n' : '';
result += '\n';
classes.forEach((c) => {
if (useRecordTypes) {
result += `public record ${normalizeCase(c.key)}(\n`;
}
else {
result += `public class ${normalizeCase(c.key)}\n`;
result += '{\n';
}
if (!useRecordTypes && generateImmutableClasses) {
result += `\tpublic ${normalizeCase(c.key)}(\n`;
c.props.forEach((p) => {
const propType = getPropType(p);
result += `\t\t${propType.type}${propType.nullable} ${convertToCamelCase(p.name)},\n`;
});
result = result.replace(/,\n$/, '\n');
result += '\t){\n';
c.props.forEach((p) => {
result += `\t\tthis.${normalizeCase(p.name)} = ${convertToCamelCase(p.name)};\n`;
});
result += '\t}\n\n';
}
c.props.forEach((p) => {
const scope = useRecordTypes ? 'property: ' : '';
if (addJsonProperty) {
if (nullValueHandlingIgnore) {
result += `\t[${scope}JsonProperty("${p.name}", NullValueHandling = NullValueHandling.Ignore)]\n`;
}
else {
result += `\t[${scope}JsonProperty("${p.name}")]\n`;
}
}
if (addJsonPropertyName) {
result += `\t[${scope}JsonPropertyName("${p.name}")]\n`;
}
const propType = getPropType(p);
if (useRecordTypes) {
result += `\t${propType.type}${propType.nullable} ${normalizeCase(p.name)},\n`;
}
else {
const newList = useReadonlyLists && p.isArray ? ` = new ${propType.type};` : '';
if (useFields) {
result += `\tpublic ${propType.type}${propType.nullable} ${normalizeCase(p.name)}${(newList || ';')}`;
}
else if (generateImmutableClasses || (p.isArray && useReadonlyLists)) {
result += `\tpublic ${propType.type}${propType.nullable} ${normalizeCase(p.name)} { get; }${newList}`;
}
else {
result += `\tpublic ${propType.type}${propType.nullable} ${normalizeCase(p.name)} { get; set; }${newList}`;
}
result += '\n';
}
});
if (useRecordTypes) {
result = result.replace(/,\n$/, '\n');
result += ');\n\n';
}
else {
result += '}\n\n';
}
});
return result.trim();
}
export default json2csharp;