JSON to C++ Struct Generator
Generate C++ structs with nlohmann/json deserializers from JSON data. Produces typed fields with proper type mapping including std::vector, std::optional, and nested struct generation.
Features
âī¸ Modern C++ Types
- std::string for string fields
- std::vector<T> for arrays
- std::optional<T> for nullable fields
- Nested struct generation
đĻ nlohmann/json
- from_json() deserializers
- j.at("key").get_to(field) pattern
- Header-only library support
- Automatic #include headers
đ§ Type Mapping
- JSON integer â int
- JSON float â double
- JSON boolean â bool
- JSON null â std::optional
C++ nlohmann/json Guide
Using nlohmann/json
nlohmann/json is a popular header-only C++ library for JSON. Add it to your project and define from_json() for automatic deserialization.
// Install via CMake or download single header: // https://github.com/nlohmann/json/releases // #include <nlohmann/json.hpp>
#include <string>
#include <nlohmann/json.hpp>
struct User {
int id;
std::string name;
bool active;
};
void from_json(const nlohmann::json& j, User& o) {
j.at("id").get_to(o.id);
j.at("name").get_to(o.name);
j.at("active").get_to(o.active);
}
// Usage:
// nlohmann::json j = nlohmann::json::parse(jsonString);
// User u = j.get<User>();
Practical notes for C++ JSON models
nlohmann/json makes JSON feel native in modern C++, and generated structs with to_json and from_json let you convert whole objects in one line. A few details matter once the code runs against real data.
Tips and common pitfalls
- Use
j.at("key")when a field is required (it throws if missing) andj.value("key", default)when it is optional. - The
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVEmacro can replace hand-written conversion functions for simple structs. - Catch
nlohmann::json::exceptionaround parsing untrusted input; malformed JSON throwsparse_error. - For very large or performance-critical payloads, consider simdjson or RapidJSON, which parse much faster at the cost of convenience.
More questions
How do I parse JSON from a file?
Open an std::ifstream and call nlohmann::json::parse(file), then convert with auto cfg = j.get<Config>();.
Are integers and floats kept apart?
Yes. nlohmann/json stores integers, unsigned integers and floating point numbers separately, so get<int>() on a whole number returns it exactly.