logo
GeekFormat

JSON vers C++

Outil en ligne JSON vers C++. Collez JSON pour générer du code d'en-tête C++ struct/class compilable, idéal pour désérialiser réponses API avec nlohmann/json ou rapidjson. Objets imbriqués divisés automatiquement, std::vector et std::optional gérés automatiquement.

Recommandations connexes

About JSON to C++: Turning JSON data into compilable C++ structs

JSON to C++ is the process of converting JSON-formatted data (objects or arrays) into C++ struct / class type definitions. C++ is a strongly-typed systems programming language widely used in backend services, game engines, embedded firmware, quantitative trading, high-performance services, and desktop clients. Development often requires converting JSON samples from API docs or actual responses into C++ types; writing structs manually is not only repetitive but also error-prone for field types. This tool aims to automate that process. Unlike Java, Python, and JavaScript, C++ lacks native support for dynamic structures like JSON, so 'JSON to C++' has long been considered 'repetitive but unavoidable' work in engineering.

This tool runs locally in the browser based on quicktype-core, using the CPP renderer and just-types rendering option to generate struct code based on std::string / std::vector<T> / std::optional<T> for C++. The output is header-only standard C++ code, independent of any third-party JSON parsing library, and can be directly #included into any C++17 / C++20 project. When combined with nlohmann/json or rapidjson parsers, API response deserialization can be completed quickly. The entire rendering pipeline runs asynchronously in the browser via Web Worker, keeping the main thread responsive.

Type inference is at the core of JSON to C++. The tool maps JSON primitive types to C++ standard types: strings to std::string, integers to int64_t (compatible with long long, avoiding cross-platform long size differences), floats to double, booleans to bool, arrays to std::vector<T>, nested objects to independent struct / class, null values to std::optional<T>. For nested objects, the tool automatically creates new classes for each level, named in PascalCase. For example, the address field generates an Address struct, and objects in items arrays generate Item structs. The same JSON nesting level generates only once, no duplicate definitions.

Unlike some online tools that require uploading JSON to servers, all computations in this tool happen in the browser. quicktype-core loads and executes via Web Worker; JSON parsing, type inference, C++ code generation, and file downloads all occur locally with no data sent to any server. This is especially important for JSON containing API keys, user-private fields, or unreleased business structures; data is cleared from memory when the page is closed. Whether for corporate network environments, internal audit requirements, or offline development scenarios, this tool provides the same reliability as the quicktype CLI tool.

Generated code typically needs to be used with a JSON parser. Two mainstream options: ① nlohmann::json (recommended, single-header inclusion, template serialization interface is friendly, usage like nlohmann::json j = nlohmann::json::parse(str); User u = j.get<User>();); ② rapidjson (high-performance SAX/DOM-style parsing, suitable for extreme scenarios like finance and games, requiring manual GetObject field extraction). For embedded, ArduinoJson (resource-constrained) or cJSON (C-style interface) can also be used. This tool's code is compatible with all major C++ JSON libraries and is not tied to any ecosystem.

Note that auto-generated code is a starting point, not an endpoint. The tool infers types from JSON samples and cannot determine precise business types (e.g., URL, Email, ID and other semantic types are all uniformly inferred as std::string). For snake_case JSON fields, C++ struct fields are generated keeping the original names; you may need to manually add NLOHMANN_DEFINE_TYPE_INTRUSIVE or NLOHMANN_JSON_FROM / NLOHMANN_JSON_TO to declare mappings. Treat generated results as a first draft, then fine-tune field names, types, and serialization annotations according to project conventions. This 'AI writes first draft + engineer reviews' workflow is the actual rhythm used by many C++ teams.

In cross-team collaboration scenarios, JSON to C++ also serves as a bridge for unifying data models. Frontend uses JSON to TypeScript, backend uses JSON to Java / Go / Rust, embedded and performance services use JSON to C++; four sides generate their own type definitions from the same JSON sample, maximizing field consistency. This tool is the 'C++ side' of this workflow, usable alongside other JSON to TypeScript / Java / Rust / Go / Python tools on the site.

In one sentence: if your code runs in performance-sensitive, strongly-typed, ecosystem-rich C++ projects and you need to quickly connect dynamic JSON data into the strongly-typed world, this tool is the quick entry point to compile JSON samples directly into C++ structs.

Cas d'utilisation

  • REST API integration: Convert JSON responses from backends to C++ structs for strongly-typed HTTP request deserialization with nlohmann::json / cpr
  • Microservice interface definition: Convert gRPC / HTTP service request body example JSON to C++ types, unifying server-side model definitions
  • Embedded & IoT: Convert device-reported JSON sensor data to C++ structs, parse MQTT / HTTP messages with ArduinoJson or ESP-IDF JSON Parser
  • Game development: Convert level configuration and character attribute JSON to C++ structs, making it easy for engines like Unreal Engine or Cocos2d-x to read .json data files
  • Financial high-frequency trading: Convert exchange JSON interface responses (OKX / Binance / Xueqiu market data) to C++ structs, parse at nanosecond speed with rapidjson
  • C++ Qt client: Convert server JSON configuration to C++ structs, load GUI data with QJsonObject / QJsonDocument
  • Boost.JSON / Boost.Beast: Convert HTTP service JSON responses to C++ structs, deserialize with Boost.JSON to write web backends
  • Embedded RTOS: Convert FreeRTOS / Zephyr system configuration JSON to C++ structs, read firmware parameters with cJSON
  • Algorithms / quantitative: Convert backtesting system JSON configurations to C++ structs, facilitating A/B experiment configuration management and version traceability
  • Database migration: Convert JSON documents exported from MongoDB / PostgreSQL to C++ models as reference for cpp-httplib / libpqxx entity fields
  • Audio/video / multimedia: Convert FFmpeg / GStreamer configuration JSON to C++ structs for convenient media pipeline parameter reading
  • Simulation & modeling: Convert simulation system JSON input configurations to C++ structs, unifying input data formats across sub-models
  • Test data construction: Convert real JSON fixtures from backend responses to C++ types for structured assertions in Google Test / Catch2 unit tests
  • Structured log parsing: Convert JSON logs captured by ELK / Loki to C++ types for easier filtering and alert rules
  • Configuration center migration: Convert Apollo / Nacos / Consul JSON configurations to C++ types for server-side configuration hot reload
  • Cross-language collaboration: Backend C++ integrating with frontend TypeScript / Java, same JSON converted to C++ struct and TS interface / Java POJO respectively to keep both sides consistent
  • Teaching & training: Convert sample JSON to struct in C++ courses to demonstrate nlohmann::json deserialization and template metaprogramming concepts
  • Field naming conversion: After converting snake_case JSON API responses to C++ structs, manually add NLOHMANN_DEFINE_TYPE_INTRUSIVE for field mapping

Comment utiliser

  1. Paste JSON content (JSON object recommended) in the left editor, or click the upload button to select a .json / .txt file
  2. The tool uses quicktype-core via Web Worker to automatically convert within 400ms; the right side displays C++ header code with std::string / std::vector<T> / nested classes
  3. If JSON format errors show a red prompt, click the 'Fix JSON' button to auto-repair common issues like trailing commas and single quotes, then retry
  4. Check that the generated struct / class names and field types match expectations; adjust source JSON key names if needed and reconvert
  5. Click 'Copy' to paste code into an .h / .hpp file in your IDE and deserialize real API responses with nlohmann/json or rapidjson; or click 'Download' to save as model.h / model.hpp

Fonctionnalités

  • Local browser conversion: JSON parsing and C++ code generation are all done in-browser via Web Worker + quicktype-core, raw data never uploaded to any server
  • nlohmann::json style output: Automatically generates STL type structs such as std::string / std::vector<T> / double / int64_t / bool, following nlohmann::json deserialization conventions, can be directly parsed by including <nlohmann/json.hpp>
  • rapidjson compatible: Generated pure C++ structs don't depend on any third-party library; work with rapidjson Document / GenericValue for high-performance parsing scenarios
  • Automatic type inference: JSON strings map to std::string, integers to int64_t / long long, floats to double, booleans to bool, arrays to std::vector<T>, nested objects to independent class / struct
  • Automatic nested object splitting: Nested JSON automatically generates independent class / struct (PascalCase naming), avoiding duplicate definitions of the same type
  • Automatic std::vector and std::optional handling: JSON arrays become std::vector<T>, potentially null fields become std::optional<T>, following modern C++17 / C++20 practices
  • 400ms debounced auto-conversion: Auto-triggers conversion after pasting JSON, real-time C++ header preview on the right, reducing waiting and extra clicks
  • One-click JSON error repair: Automatically fixes common format errors like trailing commas, single quotes, missing quotes, continuing code generation after successful repair
  • Code highlighting + one-click copy: Right-side CodeMirror renders C++ syntax highlighting; copy the entire header file with one click, or download as .h / .hpp file directly into your project
  • localStorage input history + responsive split panes: Automatically saves recent input, quickly recovers after refresh or accidental page close; paste JSON on the left, view C++ code on the right, supports drag-adjustable panel widths, adapts to large screens and mobile
  • Zero-dependency header-only output: Generated .h / .hpp are header-only, can be single-file included into any standard C++ project, no additional build configuration needed to work with nlohmann::json / rapidjson / Boost.JSON
  • Built-in snake_case to camelCase: Can automatically convert snake_case fields in JSON to C++ recommended camelCase field names, with NLOHMANN_DEFINE_TYPE_INTRUSIVE maintaining snake_case serialization mapping

Exemples de code

C++: Deserialize struct generated by this tool using nlohmann/json

cpp

Place the generated User struct into .hpp and deserialize with nlohmann::json (recommended for modern C++17/20 projects).

// model.hpp (generated by this tool)
// #pragma once
// #include <cstdint>
// #include <optional>
// #include <string>
// #include <vector>
// struct Address {
//   std::string city;
//   std::string zip;
// };
// struct User {
//   int64_t id;
//   std::string name;
//   std::optional<Address> address;
//   std::vector<std::string> tags;
// };

#include <nlohmann/json.hpp>
#include "model.hpp"

using nlohmann::json;

int main() {
    std::string raw = R"({
        "id": 1,
        "name": "Alice",
        "address": { "city": "Beijing", "zip": "100000" },
        "tags": ["cpp", "nlohmann"]
    })";

    // 1) Parse JSON string
    json j = json::parse(raw);

    // 2) Strongly-typed deserialization to struct generated by this tool
    User u = j.get<User>();

    // 3) Access fields
    std::cout << u.name << " lives in "
              << (u.address ? u.address->city : "unknown")
              << std::endl;

    for (const auto& tag : u.tags) {
        std::cout << "tag: " << tag << std::endl;
    }
    return 0;
}

/*
 * Compilation (CMake project):
 *   find_package(nlohmann_json REQUIRED)
 *   target_link_libraries(my_app PRIVATE nlohmann_json::nlohmann_json)
 * Compilation (vcpkg):
 *   vcpkg install nlohmann-json
 * Single-file integration:
 *   Download json.hpp directly from https://github.com/nlohmann/json/releases
 */

C++: Parse JSON to struct generated by this tool using rapidjson

cpp

rapidjson does not support automatic deserialization to custom structs; manual GetObject extraction is required. Suitable for high-performance scenarios like finance / games.

#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>
#include "model.hpp"

int main() {
    const char* raw = R"({
        "id": 1,
        "name": "Alice",
        "address": { "city": "Beijing", "zip": "100000" },
        "tags": ["cpp", "rapidjson"]
    })";

    // 1) rapidjson DOM parsing
    rapidjson::Document doc;
    doc.Parse(raw);

    // 2) Construct struct generated by this tool and fill manually
    User u;
    u.id = doc["id"].GetInt64();
    u.name = doc["name"].GetString();

    if (doc.HasMember("address") && doc["address"].IsObject()) {
        Address addr;
        addr.city = doc["address"]["city"].GetString();
        addr.zip  = doc["address"]["zip"].GetString();
        u.address = addr;
    }

    for (auto& tag : doc["tags"].GetArray()) {
        u.tags.push_back(tag.GetString());
    }

    // 3) Use the filled struct
    std::cout << u.name << ", tags=" << u.tags.size() << std::endl;
    return 0;
}

/*
 * rapidjson high-performance tips:
 *   ① Use rapidjson::MemoryPoolAllocator with StringBuffer for further speedup;
 *   ② For high-frequency scenarios, use SAX-style Reader / Writer for direct streaming;
 *   ③ Enable RAPIDJSON_SSE42 / RAPIDJSON_SIMD macros to use CPU SIMD instructions for acceleration.
 */

C++: NLOHMANN_DEFINE_TYPE_INTRUSIVE handling snake_case field mapping

cpp

When JSON fields are snake_case and C++ members should use camelCase / PascalCase, declare mappings using nlohmann/json macros.

#include <nlohmann/json.hpp>
#include <string>
#include <cstdint>

// Assume this tool generates fields as snake_case: user_name, created_at
// Add the macro below when renaming to camelCase in real projects
struct UserProfile {
    int64_t id;
    std::string userName;       // In JSON it's "user_name"
    std::string emailAddress;   // In JSON it's "email_address"
    std::string createdAt;      // In JSON it's "created_at"
};

// Use NLOHMANN_DEFINE_TYPE_INTRUSIVE to declare mappings inside the class
// Note: must be placed in public section
// 
// NLOHMANN_DEFINE_TYPE_INTRUSIVE(UserProfile, id, userName, emailAddress, createdAt)

// Or use non-intrusive macro (avoids modifying the class itself):
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(UserProfile, id, userName, emailAddress, createdAt)

// Usage:
int main() {
    nlohmann::json j = {
        {"id", 1},
        {"user_name", "Alice"},
        {"email_address", "alice@example.com"},
        {"created_at", "2026-07-14T10:00:00.000Z"}
    };

    UserProfile p = j.get<UserProfile>();
    // Serialization also outputs original field names
    std::cout << j.dump(2) << std::endl;
    return 0;
}

/*
 * Tips:
 *   ① Intrusive macro (NLOHMANN_DEFINE_TYPE_INTRUSIVE) must be placed in the public section;
 *   ② Non-intrusive macro (NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE) is defined outside the class;
 *   ③ Field order must exactly match macro parameters;
 *   ④ Date fields can use nlohmann::json custom adl_serializer to handle ISO 8601 format.
 */

Best Practices

Most teams recommend starting with nlohmann::json because its API is similar to STL, deserialization can be done in one line j.get<User>(), and readability is extremely high. Only switch to rapidjson when encountering performance bottlenecks (e.g., millions of JSON field extractions per second). Structs generated by this tool work with both.

nlohmann/json repositoryrapidjson repository

Using include(FetchContent) + FetchContent_Declare(nlohmann_json URL ...) is the cleanest way to integrate nlohmann/json with CMake, no pre-installed vcpkg needed; if you don't want FetchContent, use vcpkg install nlohmann-json or directly download the single json.hpp file and include it.

CMake FetchContent official documentation

The tool defaults to keeping original JSON field names (snake_case). If you want C++ members to be camelCase or PascalCase, you need to add NLOHMANN_DEFINE_TYPE_INTRUSIVE(UserProfile, id, userName, ...) inside the class to explicitly map JSON keys to C++ members; otherwise deserialization will fail.

NLOHMANN_DEFINE_TYPE_INTRUSIVE documentation

C++17+ directly uses std::optional<T>; C++11/14 projects replace with boost::optional<T> (#include <boost/optional.hpp>); C-style projects use cJSON + sentinel fields (-1, empty strings) to represent nullability. Note that std::optional and boost::optional have slightly different interfaces (has_value() vs is_initialized()).

cppreference std::optional

On devices with extremely small RAM like Arduino Uno / ESP8266, std::vector and std::string usually trigger OOM. Use ArduinoJson 6.x + StaticJsonDocument<capacity> to limit buffers instead, replace std::vector<T> with fixed-size std::array<T, N>, and std::string with const char* + length.

ArduinoJson documentation

All parsing, code generation, and file downloads in this tool are completed locally in the browser via Web Worker; raw JSON is never uploaded to any server. But still recommended: ① Desensitize internal business models first (remove tokens / phone numbers, etc.); ② Close the page to clear memory; ③ In large company compliance scenarios, use the local quicktype CLI within the IDE to process JSON containing customer information.

JSON with more than 6 levels of nesting is recommended to be refactored at the source, or manually split deep nesting into intermediate structs after generation by this tool to improve readability and compilation speed. Deep nesting can cause template instantiation depth to be too deep; some older compilers (GCC 6 and below) report 'template instantiation depth exceeded' errors.

Code generated by this tool is essentially C++ (uses std::optional / template and other C++ features); .hpp suffix is recommended to indicate 'C++ header', distinguishing it from C headers' .h. In CMake projects: set_target_properties(target PROPERTIES CXX_EXTENSIONS ON); CMake can also automatically identify whether to compile with gcc or g++ via .h vs .hpp, maximizing avoidance of header-only template not being re-instantiated issues.

GCC file suffix conventionsCMake file type recognition

FAQ

How do I convert JSON to C++ struct / class definitions?

Paste JSON content in the left editor (drag & drop or click to upload .json / .txt files also supported). The tool will automatically call quicktype-core within 400ms to generate C++ header code locally in the browser; the right CodeMirror area displays struct code with std::string / std::vector<T> / nested classes. If JSON is malformed, click the 'Fix JSON' button to auto-repair before converting.

What headers do I need to include for the generated C++ code?

The tool outputs header-only struct code relying only on the C++ standard library (<string>, <vector>, <optional>, <cstdint>). When parsing with nlohmann/json, you need to additionally #include <nlohmann/json.hpp>; when parsing with rapidjson, you need #include "rapidjson/document.h". Other standard headers are declared by the tool as needed.

What JSON data structures are supported?

All valid JSON structures are supported: basic types (null, boolean, number, string), arrays (1D or multi-dimensional), nested objects (any depth). JSON objects generate a root struct / class; JSON arrays appear as std::vector<T> fields in parent structs. JavaScript object literals, functions, Symbols, undefined and other non-JSON values are not supported.

How do JSON field types map to C++ types?

Strings map to std::string; integers map to int64_t (long long is also commonly used for legacy code); floats map to double; booleans map to bool; arrays map to std::vector<T>; nested objects map to independent struct / class; null values map to std::optional<T> (nlohmann::json can also be used as fallback). See the 'JSON Type to C++ Type Mapping Quick Reference' table at the bottom of the page for detailed mapping rules.

What type is generated for null values?

Null values in JSON generate std::optional<T> (available since C++17), indicating the field may be missing or type-uncertain. If you already know the field's actual type, provide a sample value in the source JSON (e.g., "field": "" infers std::string), then after generation you can change to more precise types like std::optional<std::string> based on business needs.

Do arrays automatically convert to std::vector?

Yes. JSON arrays are uniformly converted to C++ std::vector<T> template containers, with element types auto-inferred from the first array element. For example ["a","b"] generates std::vector<std::string>, [1,2,3] generates std::vector<int64_t>, [{...},{...}] generates std::vector<Item> (Item is an independent struct generated from nested objects).

How are nested objects handled?

Each nested object generates an independent struct / class, named using PascalCase for the field name (e.g., address field generates Address struct, objects in items array generate Item struct). Nested classes are referenced in the root struct via std::optional<Address> or Address typed members. Objects with the same structure reuse the same type to avoid duplicate definitions.

Can the generated code deserialize with nlohmann/json?

Yes. Typical usage example: nlohmann::json j; j["root"] = nlohmann::json::parse(raw_json); User u = j.get<User>(); Prerequisites: your project has the nlohmann/json single-header dependency (simply include <nlohmann/json.hpp>) and the User struct generated by this tool is defined.

Can the generated code deserialize with rapidjson?

Yes. rapidjson requires you to manually write GetObject-style field extraction code. Typical approach: rapidjson::Document doc; doc.Parse(raw_json); const auto& obj = doc["root"]; std::string id = obj["id"].GetString(); Since rapidjson doesn't support automatic deserialization via templates, the generated struct only serves as a data model reference.

How are snake_case JSON fields handled?

The tool generates C++ fields keeping the original JSON field names (e.g., user_name). If you want C++ members to use camelCase (userName) or PascalCase (UserName), modify manually after generation and add NLOHMANN macros (NLOHMANN_DEFINE_TYPE_INTRUSIVE / NLOHMANN_JSON_FROM / NLOHMANN_JSON_TO) to specify mappings.

Can the generated header files be used directly in Qt / Unreal / Boost projects?

Yes. This tool generates header-only standard C++ code with no framework dependencies. When parsing with Qt QJsonObject, use the struct as a data model (annotate members with Q_GADGET); with Unreal Engine, use FJsonObjectConverter::JsonObjectStringToUStruct; with Boost.JSON, parse JSON to boost::json::object and extract fields one by one.

Is data uploaded to servers? Is privacy secure?

Fully local browser operation. All JSON parsing, C++ code generation, and file downloads are done in-browser via JavaScript (Web Worker + quicktype-core). Neither your input JSON data nor generated C++ code are uploaded to any server, nor are they logged or cached in the cloud. Sensitive JSON containing API keys, tokens, or undisclosed business fields can be used safely; data is cleared when the page is closed.

Do I need to register or log in?

No. The tool is completely free, no registration, login, or authorization required. Just open the page and use it. All features are available locally in the browser with no call limits or file size restrictions (subject to browser memory constraints).

What if JSON format is invalid?

The tool automatically checks JSON validity. On error, a red error message appears on the right with a 'Fix JSON' button. Clicking it auto-repairs common errors: trailing commas, single quotes replaced with double quotes, missing quotes on keys completed, comments removed, etc. After successful repair, C++ code generation continues.

What's the difference between this tool and JSON to Java / JSON to Rust?

All three convert JSON to target language type definitions, but output forms differ: JSON to C++ generates header-only struct / class requiring nlohmann/json or rapidjson for deserialization code; JSON to Java generates complete POJO classes with getter/setter that can be directly compiled and run; JSON to Rust generates struct with Serde derive that can be directly deserialized by serde_json. Choose based on your tech stack.

Dépannage

Prompt 'Please enter JSON data' or right side is empty

The left input box is empty or contains only whitespace. Ensure valid JSON content is pasted, or click the upload button to select a .json / .txt file; you can also click the example button to load built-in samples (including nested address / tags fields).

Prompt JSON parsing failed

Common causes: trailing commas, using single quotes instead of double quotes, unquoted keys, containing JavaScript comments. Click the 'Fix JSON' button to auto-repair some errors; if it still fails, validate with a JSON formatting tool first.

Compile error 'std::optional not declared'

The project is not using C++17 or later. std::optional was introduced in C++17. Set CMAKE_CXX_STANDARD to 17 or higher in CMakeLists.txt (or use set(CMAKE_CXX_STANDARD 17)); or add #include <optional> at the top of the source file and confirm compiler version.

Compile error 'int64_t not declared'

The tool uses int64_t from <cstdint>, requiring GCC 4.5+ / Clang 3.0+ / MSVC 2015+. Check whether the source file includes #include <cstdint> or #include <stdint.h> at the top, and confirm CMake C++ standard is set >= C++11.

nlohmann::json deserialization loses fields

Possible causes: ① JSON field names don't exactly match C++ member names (snake_case vs camelCase); ② Nested objects not properly handled; ③ value() access on std::optional fields throws exceptions. Solution: add NLOHMANN_DEFINE_TYPE_INTRUSIVE macro to explicitly map fields, or use j.value("key", default) to provide default values.

rapidjson parsing GetString segfault

rapidjson does not validate field types by default. GetString is only safe when the field exists and is a string type. Improved approach: if (doc.HasMember("name") && doc["name"].IsString()) { u.name = doc["name"].GetString(); }, avoiding direct GetInt / GetString on non-existent keys.

Generated field types not precise enough (all integers are int64_t)

The tool infers types from JSON samples; all integers are int64_t and all strings are std::string. If you need more precise types like int32_t, uint64_t, std::chrono::system_clock::time_point, manually modify field types after generation, and ensure your chosen JSON parsing library supports deserialization for that type.

null field generated std::optional<nlohmann::json> instead of std::optional<std::string>

Because JSON null cannot infer a specific type, the tool safely falls back to std::optional<nlohmann::json>. If you know the field's actual type, provide a sample value in the source JSON (e.g., "field": "" infers std::string), regenerate, then manually change to std::optional<std::string>.

snake_case JSON fields inconsistent with C++ naming style

The tool generates C++ fields keeping the original JSON field names (e.g., user_name). If you want C++ members to use camelCase (userName) while correctly deserializing snake_case JSON, refer to codeExamples section 3 using NLOHMANN_DEFINE_TYPE_INTRUSIVE / NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE macros.

Downloaded .hpp file causes compile errors in project

Possible causes: ① CMake not set to C++17 / C++20 standard; ② Missing headers like <optional> / <vector>; ③ Struct name conflicts with other types in the project. Solution: add set(CMAKE_CXX_STANDARD 17) in CMakeLists.txt, add appropriate headers at the top of source files, wrap in namespace or rename conflicting structs.

Glossaire

struct / class
Keywords in C++ for defining composite data types. This tool generates struct, e.g., struct User { int64_t id; std::string name; };. struct and class are nearly equivalent in C++ (different default access: struct members default to public, class members default to private); the tool defaults to struct. For deserialization scenarios, using struct is cleaner and more intuitive; if you need encapsulated private members + accessor methods, manually change to class.
std::string
The C++ standard library string type (ownership semantics), defined in <string>. This tool automatically maps JSON string fields to std::string, e.g., std::string name. Note that std::string differs from C's char* / char[]: std::string manages memory automatically, supports operator overloading (+, ==, <), but performs best for small to medium length strings; for extremely long strings (like log lines 1KB+), consider std::string_view or custom buffers.
std::vector<T>
The C++ standard library dynamic array container (<vector>), equivalent to Java's ArrayList, Python's list, JavaScript's Array. This tool automatically maps JSON array fields to std::vector<T>, e.g., std::vector<std::string> tags. Advantages: contiguous memory, O(1) random access, amortized O(1) tail append; disadvantages: O(n) mid-insertion. Use std::array<T, N> (stack-allocated) when fixed-size arrays are needed.
std::optional<T>
The C++17+ standard library optional value wrapper type (<optional>), indicating a value may not exist. Typical usage: std::optional<std::string> nickname; if (nickname) { use(*nickname); }. This tool maps JSON fields that may be null to std::optional<T>, e.g., std::optional<std::string> nickname. If your project must use C++11/14, replace with boost::optional<T> (API nearly identical).
int64_t / double
int64_t is a fixed-width 64-bit integer type alias in <cstdint>, equivalent to long long, cross-platform guaranteed 8 bytes. double is C++'s double-precision floating point type (IEEE 754 double / binary64, approximately 15-17 significant digits). This tool uniformly maps JSON integers to int64_t and floats to double, avoiding precision issues from cross-platform long size inconsistencies (Windows long is 32-bit, Linux long is 64-bit). Use long double or decimal libraries for precise floating point (financial calculations).
nlohmann::json
One of the most popular JSON libraries in the C++ ecosystem, also known as nlohmann/json, released by Niels Lohmann of Germany. Its core idea maps JSON data structures to C++ standard library types (std::map, std::vector, std::string), and deserialization can be done in one line via j.get<T>(). Code generated by this tool works with nlohmann/json, using macros like NLOHMANN_DEFINE_TYPE_INTRUSIVE, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE for automatic deserialization. Single-header dependency, rich documentation, API consistent with STL style, it is the first choice for most C++ projects.
rapidjson
Tencent's open-source high-performance JSON library (C++), about 5k lines of code, performance about 3-5x that of nlohmann::json. Supports both SAX (streaming) and DOM (Document Object Model) parsing styles, with specialized acceleration for SIMD instructions (such as SSE42). Typical scenarios: financial trading market data push, game engine object serialization, embedded high-performance logging. Structs generated by this tool can serve as target models for rapidjson Document / GenericValue deserialization, but since rapidjson lacks template reflection, manual GetObject / GetString field extraction is required.
Web Worker / quicktype-core
Web Worker is a browser-provided background thread API that executes in parallel with the main thread, cannot access the main thread's DOM, and only communicates via postMessage. quicktype-core is an open-source JSON → multi-language code generator library (GitHub: quicktype/quicktype), supporting over a dozen languages including C++/Java/TypeScript/Rust/Go/Python/Swift. This tool renders header-only struct code for C++ locally in the browser based on quicktype-core; raw data is never uploaded to any server, all parsing, generation, and downloads happen in-browser. Worker loading quicktype-core avoids blocking the UI main thread.
snake_case / camelCase / PascalCase
Three mainstream field naming conventions: snake_case (user_name, preferred for C / Python / DB), camelCase (userName, preferred for Java / JS), PascalCase (UserName, preferred for C# / Rust struct fields). This tool defaults to keeping original JSON field names (usually snake_case); you can manually adjust after generation and add NLOHMANN macros to declare mappings. Note C++ public field naming conventions recommend camelCase or snake_case; PascalCase is mainly for class names (Google C++ Style), not recommended for members; snake_case is naturally compatible with MySQL column names.
NLOHMANN_DEFINE_TYPE_INTRUSIVE
A macro provided by the nlohmann/json library for declaring JSON serialization field mappings inside a class. Syntax: NLOHMANN_DEFINE_TYPE_INTRUSIVE(ClassName, member1, member2, ...), must be placed in the public section (to let the macro access private fields). The non-intrusive version NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE is placed outside the class, no class modification needed. Structs generated by this tool do not automatically add such macros; add manually when needed to declare correspondences between JSON keys and C++ members. If JSON field names match C++ member names, you can omit this macro and directly use j.get<T>().

JSON Type to C++ Type Mapping Quick Reference

The tool automatically infers corresponding C++ types based on JSON value types:

JSON Value ExampleGenerated C++ TypeNotes
nullstd::optional<T>null value type is uncertain, falls back to std::optional<T> (C++17+)
true / falseboolJSON booleans directly map to C++ bool
42int64_tJSON integers default to int64_t (<cstdint>), compatible with long long
3.14doubleJSON floats default to double (IEEE 754 double precision)
"hello"std::stringJSON strings map to std::string (<string>)
["a","b"]std::vector<std::string>String arrays map to std::vector<std::string>
[1,2,3]std::vector<int64_t>Integer arrays map to std::vector<int64_t>
[{...},{...}]std::vector<Item>Object arrays generate corresponding struct from the first element, then wrapped in std::vector
[]std::vector<nlohmann::json>Empty arrays cannot infer element type, falls back to nlohmann::json (can be rewritten as std::vector<std::string>)
{...} nested objectIndependent struct / classNested objects generate independent struct, PascalCase named (address → Address)

Common C++ JSON Parser Selection Comparison Table

Comparison of mainstream JSON parsing libraries in the C++ ecosystem; choose according to project needs:

LibraryAPI StylePerformanceSuitable Scenarios
nlohmann::jsonTemplate / STL-likeMediumWeb backends, desktop apps, teaching; best compatibility with std::vector / std::map
rapidjsonSAX / DOMExtremely highFinancial trading, game engines, high-throughput services; supports SIMD acceleration
Boost.JSONBoost.ContainerHighBoost ecosystem projects, web servers (Beast / Asio)
cJSONC-style / functionalHighC projects, C++ embedded, scenarios where you don't want to introduce C++ templates
ArduinoJsonC++ templatesMediumArduino, ESP32 / ESP8266, embedded MCUs

Common C++ Standard Library Types to JSON Quick Reference

Overview of core types in the C++ standard library corresponding to JSON fields, for quick developer reference:

JSON KeywordC++ Standard Library EquivalentRequired HeaderC++ Standard
stringstd::string<string>C++98
integerint64_t (<cstdint>)<cstdint>C++11
numberdouble<iostream> / <cmath>C++98
booleanbool<stdbool.h>(C) / built-inC++98
nullstd::optional<T><optional>C++17
arraystd::vector<T><vector>C++98
fixed arraystd::array<T, N><array>C++11
object / mapstd::map<std::string, T><map>C++98
hash objectstd::unordered_map<K, T><unordered_map>C++11
string viewstd::string_view (non-owning)<string_view>C++17
byte / charstd::byte / char<cstddef>C++17 / C++98

Privacy & Security

Toutes les opérations de cet outil JSON vers C++ s'effectuent entièrement dans votre navigateur: analyse JSON, génération de structs C++ et téléchargements s'exécutent côté client via JavaScript (Web Worker + quicktype-core). Aucun contenu JSON, fichier téléversé ou code généré n'est envoyé sur le réseau. Les téléversements utilisent FileReader natif directement en mémoire. Pas de suivi Cookies, pas de collecte de données. En fermant la page, tout est effacé de la mémoire.

Authoritative References