मुख्य सामग्री पर जाएँ

JSON से Rust Struct

JSON को serde Serialize/Deserialize, rename_all, वैकल्पिक फ़ील्ड के लिए Option और keyword के लिए raw identifier वाले Rust struct में बदलें। rustfmt-रेडी।

100% क्लाइंट-साइड · कोई भी डेटा आपके ब्राउज़र को नहीं छोड़ता

skip_serializing_if on optional fields

Rust — 3 types
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Root {
    pub id: i64,
    pub username: String,
    pub email: String,
    pub is_active: bool,
    pub rating: f64,
    pub created_at: String,
    pub avatar_url: serde_json::Value,
    pub tags: Vec<String>,
    pub address: Address,
    pub orders: Vec<Order>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Address {
    pub street: String,
    pub city: String,
    pub zip_code: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Order {
    pub order_id: String,
    pub total: f64,
    pub items: i64,
    pub shipped: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coupon: Option<String>,
}

Arrays of objects are merged: a key missing from some items becomes optional, null makes a field nullable, and identical shapes share one type. Paste several examples in an array for the most accurate types.

इस टूल के बारे में

JSON पेस्ट करें और ऐसे Rust struct पाएँ जिनमें serde उस JSON को deserialize कर सके। फ़ील्ड snake_case में होते हैं, और टूल आपकी key के लिए सबसे सही #[serde(rename_all)] नियम चुनता है (camelCase, PascalCase, kebab-case…) और #[serde(rename)] सिर्फ़ वहीं जोड़ता है जहाँ ज़रूरी हो। जो key Rust के keyword हैं, वे r#type जैसे raw identifier बन जाती हैं। ऑब्जेक्ट के ऐरे मिलाए जाते हैं, इसलिए गायब key Option<T> बन जाती हैं (None होने पर छोड़ दी जाती हैं), null संभाले जाते हैं, पूर्णांक और float अलग पहचाने जाते हैं, नेस्टेड ऑब्जेक्ट को अपने struct मिलते हैं, और ID को key बनाकर रखे गए ऑब्जेक्ट HashMap बन जाते हैं। आउटपुट rustfmt की तरह फ़ॉर्मेट होता है। इसी पेज से Go, C#, Python या Kotlin पर स्विच करें।

JSON को Rust struct में कैसे बदलें

JSON सैंपल से serde struct बनाएँ।

  1. 1

    JSON पेस्ट करें

    एक JSON ऑब्जेक्ट या उदाहरणों का ऐरे पेस्ट करें।

  2. 2

    विकल्प चुनें

    रूट टाइप का नाम सेट करें और चुनें कि फ़ील्ड public हों या नहीं।

  3. 3

    कोड कॉपी करें

    struct को अपने crate में कॉपी करें; serde (derive फ़ीचर के साथ) और serde_json जोड़ें।