CMD Simulator

Handling Edge Cases in JSON to Typedef Conversion

Learn how our converter handles tricky JSON patterns: empty arrays, mixed-type arrays, deeply nested objects, special characters in keys, root-level arrays, and null-heavy data.

Common Edge Cases

Real-world JSON is rarely clean. Here's how our converter handles the tricky patterns you'll encounter.


Empty Arrays

{ "items": [] }

With no elements to inspect, the converter can't infer the type:

  • TypeScript: items: unknown[]
  • C#: public List<object> Items { get; set; }

Fix: Add at least one representative element to the array before converting.


Mixed-Type Arrays

{ "data": [1, "hello", true, null] }
  • TypeScript: data: (number | string | boolean | null)[]
  • C#: public List<object> Data { get; set; } (C# can't express union types natively)

Root-Level Arrays

When the JSON itself is an array, not an object:

[
  { "id": 1, "name": "Alice" },
  { "id": 2, "name": "Bob" }
]
  • TypeScript: Creates the interface plus a type alias: export type RootObjectArray = RootObject[]
  • C#: Creates the class plus a comment: // Root is an array: List<RootObject>

Deeply Nested Objects (5+ Levels)

{
  "level1": {
    "level2": {
      "level3": {
        "level4": {
          "level5": {
            "value": "deep"
          }
        }
      }
    }
  }
}

The converter handles arbitrary nesting depth. Each level gets its own named type. The naming follows the key hierarchy: Level1, Level2, Level3, etc.


Special Characters in Keys

{
  "first-name": "Alice",
  "2nd_place": true,
  "has space": "value",
  "$special": 42
}
  • TypeScript: Invalid identifiers are quoted: "first-name"?: string
  • C#: All keys are converted to PascalCase: FirstName, 2ndPlace (may need manual adjustment for leading digits)

Null-Heavy Data

{
  "name": "Alice",
  "phone": null,
  "address": null,
  "notes": null
}

All null fields become optional with null types:

export interface RootObject {
  name: string;
  phone?: null;
  address?: null;
  notes?: null;
}

To get better types, provide a JSON sample where nullable fields have actual values when possible.


Arrays of Objects with Different Shapes

{
  "events": [
    { "type": "click", "x": 100, "y": 200 },
    { "type": "scroll", "offset": 500 }
  ]
}

The converter merges all object shapes in the array. Fields not present in every object are marked optional:

export interface Event {
  type: string;
  x?: number;
  y?: number;
  offset?: number;
}

Primitive Root Values

"just a string"
  • TypeScript: export type RootObject = string;
  • C#: // Root value is a primitive: string

These are valid JSON but unusual. The converter handles them gracefully.

Ready to try it?

Open the Converter →