Chuyển JSON thành class C#!

Nhập JSON để tạo mã class C#, kể cả các object lồng nhau! Hỗ trợ System.Text.Json [JsonPropertyName], .NET, ASP.NET Core.
JSON
Kết quả
 

Chuyển JSON thành class C#!

Chuyển JSON thành class C# dùng cho System.Text.Json. Tên property được đổi sang PascalCase, và mỗi property đều mang attribute [JsonPropertyName] để bind đúng vào key gốc.

Công cụ giúp bỏ bớt việc sao chép rồi gõ lại cho model request và response của ASP.NET Core, kiểu dùng trong lời gọi HttpClient.GetFromJsonAsync<T>() tới API bên ngoài, và class dữ liệu trong app Unity hay MAUI.

Cách sử dụng

  1. Dán response JSON hoặc file cấu hình.
  2. Nhập tên class gốc vào Tên kiểu (ví dụ PaymentResult).
  3. Đặt các class được tạo vào file .cs và thêm namespace của bạn.
  4. Dùng với JsonSerializer.Deserialize<PaymentResult>(json) hoặc GetFromJsonAsync<PaymentResult>(url).

Ví dụ

Đầu vào (JSON)
{
  "paymentId": "pay_8f2k",
  "amount": 15000,
  "currency": "KRW",
  "approved": true,
  "approvedAt": "2024-05-01T12:30:00Z",
  "card": { "issuer": "VISA", "last4": "4242" },
  "metadata": null
}
Đầu ra (C# · System.Text.Json)
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

public class PaymentResult
{
    [JsonPropertyName("paymentId")]
    public string PaymentId { get; set; } = string.Empty;

    [JsonPropertyName("amount")]
    public int Amount { get; set; }

    [JsonPropertyName("currency")]
    public string Currency { get; set; } = string.Empty;

    [JsonPropertyName("approved")]
    public bool Approved { get; set; }

    [JsonPropertyName("approvedAt")]
    public string ApprovedAt { get; set; } = string.Empty;

    [JsonPropertyName("card")]
    public Card Card { get; set; } = new();

    [JsonPropertyName("metadata")]
    public JsonElement? Metadata { get; set; }
}

public class Card
{
    [JsonPropertyName("issuer")]
    public string Issuer { get; set; } = string.Empty;

    [JsonPropertyName("last4")]
    public string Last4 { get; set; } = string.Empty;
}

Mọi property đều có [JsonPropertyName], nên paymentId ↔ PaymentId khớp nhau bất kể quy tắc hoa/thường. metadata chỉ toàn là null nên không rõ kiểu và thành JsonElement?. Property kiểu chuỗi và object nhận initializer string.Empty / new() để code compile không có cảnh báo nullable.

Tính năng hỗ trợ

  • [JsonPropertyName("originalKey")] trên mỗi property, kèm using System.Text.Json.Serialization;.
  • Kiểu: string, int, long cho số nguyên vượt 32 bit, double cho số thập phân, bool, và List<T> cho mảng.
  • Giá trị có kiểu lẫn lộn hoặc không rõ thành JsonElement, kèm thêm using System.Text.Json;.
  • Property thiếu ở một số phần tử hoặc chứa null thành nullable (int?, string?).
  • Property bắt buộc nhận initializer = string.Empty; hoặc = new(); để tránh cảnh báo nullable reference CS8618.
  • C# không cho phép property trùng tên với class chứa nó, nên property đó được thêm hậu tố Value (ví dụ RootValue).
  • Mảng ở cấp cao nhất cho ra comment // Root: List<RootItem> cùng class phần tử.

Trường hợp sử dụng

Gọi API bên ngoài bằng HttpClient

Chuyển một response mẫu từ API thanh toán hay theo dõi vận chuyển rồi dùng làm kiểu trong await http.GetFromJsonAsync<PaymentResult>(url), thay vì lấy từng field ra khỏi JsonDocument.

Model cho payload webhook trong ASP.NET Core

Tạo class từ payload mà dịch vụ bên thứ ba POST tới bạn và nhận chúng làm tham số [FromBody], để model binding và validation chạy như bình thường.

appsettings và file dữ liệu game

Cố định cấu trúc của file dữ liệu JSON mà app Unity hay console đọc vào bằng class, khi file dữ liệu thay đổi sẽ lộ ra lỗi deserialize ngay lập tức.

Lưu ý và giới hạn

  • Không tạo output cho Newtonsoft.Json ([JsonProperty]). Nếu dùng Json.NET, hãy đổi attribute thành [JsonProperty("key")].
  • Chuỗi ngày tháng vẫn là string. Với giá trị ISO 8601, chỉ cần đổi kiểu thành DateTime hoặc DateTimeOffset là System.Text.Json parse được.
  • new() theo target-typed và string? giả định C# 9+ với nullable context đã bật (mặc định từ .NET 6).
  • Không có output record hay required. Với model bất biến, hãy đổi { get; set; } thành { get; init; }.
  • Mọi class nằm trong một khối; việc tách file và namespace do bạn tự làm.

Câu hỏi thường gặp

Vì sao vẫn thêm [JsonPropertyName] khi key đã khớp sẵn?

System.Text.Json mặc định phân biệt hoa/thường. Trong dự án console hay worker không có JsonSerializerOptions tùy biến, paymentId sẽ không bind vào PaymentId, nên attribute luôn được ghi để chạy được bất kể cấu hình.

Đọc property JsonElement? thế nào?

Kiểm tra ValueKind, rồi dùng GetString(), GetInt32() hoặc Deserialize<T>(). Khi đã biết kiểu thật, thay JsonElement bằng kiểu đó là cách gọn hơn.

Có giữ tên property dạng camelCase được không?

Output theo quy ước PascalCase của C#. Key gốc nằm trong [JsonPropertyName], nên bạn có thể thoải mái đổi tên property miễn là giữ attribute.

Có dùng được với JsonUtility của Unity không?

JsonUtility chỉ xử lý field public của class [Serializable], không xử lý property, và bỏ qua [JsonPropertyName]. Trong Unity, hãy dùng output này cùng package Newtonsoft.Json hoặc System.Text.Json.