How to Generate Code from JSON Schema
January 3, 2025 12 min read
What is Code Generation from JSON?
Code generation creates strongly-typed classes/models from JSON data or JSON Schema. This saves time, reduces errors, and ensures type safety in your applications.
Sample JSON
{
"user": {
"id": 123,
"name": "John Doe",
"email": "john@example.com",
"isActive": true,
"roles": ["admin", "user"],
"settings": {
"theme": "dark",
"notifications": true
}
}
}
Generated TypeScript
interface Settings {
theme: string;
notifications: boolean;
}
interface User {
id: number;
name: string;
email: string;
isActive: boolean;
roles: string[];
settings: Settings;
}
Generated C#
public class Settings
{
public string Theme { get; set; }
public bool Notifications { get; set; }
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public bool IsActive { get; set; }
public List Roles { get; set; }
public Settings Settings { get; set; }
}
Generated Java
public class Settings {
private String theme;
private boolean notifications;
// Getters and setters...
}
public class User {
private int id;
private String name;
private String email;
private boolean isActive;
private List roles;
private Settings settings;
// Getters and setters...
}
Generated Python
from dataclasses import dataclass
from typing import List
@dataclass
class Settings:
theme: str
notifications: bool
@dataclass
class User:
id: int
name: str
email: str
is_active: bool
roles: List[str]
settings: Settings
Generated Go
type Settings struct {
Theme string `json:"theme"`
Notifications bool `json:"notifications"`
}
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
IsActive bool `json:"isActive"`
Roles []string `json:"roles"`
Settings Settings `json:"settings"`
}
Benefits of Code Generation
- ✅ Type safety and IntelliSense
- ✅ Faster development
- ✅ Fewer runtime errors
- ✅ Consistent naming
- ✅ Easy refactoring
- ✅ Documentation from schema
Tools and Libraries
quicktype
Multi-language code generator from JSON:
quicktype data.json -o User.cs --lang csharp
json2ts
TypeScript interfaces from JSON:
npm install -g json2ts
json2ts data.json
Online Tools
Best Practices
- Use JSON Schema for complex types
- Add validation attributes
- Generate from real API responses
- Keep generated code separate
- Version control schemas
- Automate generation in CI/CD
Try it now! Generate code from your JSON:
JSON to C# |
JSON to TypeScript
Back to Blog