deploy: a47170346a
This commit is contained in:
1 parent
b36f8a9821
commit
11a863958e
1180 files changed
+14211
-6025
No files matched your search
@@ -1,4 +1,4 @@
|
||||
<!doctype html><html lang=en class=no-js> <head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><meta name=author content="Niels Lohmann"><link href="https://json.nlohmann.me/features/arbitrary_types/" rel="canonical"><link href=../ rel=prev><link href=../type_recipes/ rel=next><link rel=icon href=../../assets/images/favicon.png><meta name=generator content="mkdocs-1.6.1, mkdocs-material-9.7.7"><title>Arbitrary Type Conversions - JSON for Modern C++</title><link rel=stylesheet href=../../assets/stylesheets/main.ec1eaa64.min.css><link rel=stylesheet href=../../assets/stylesheets/palette.ab4e12ef.min.css><link rel="stylesheet" href="../../assets/external/fonts.googleapis.com/css.61a430c9.css"><style>:root{--md-text-font:"Roboto";--md-code-font:"JetBrains Mono"}</style><link rel=stylesheet href=../../css/custom.css><script>__md_scope=new URL("../..",location),__md_hash=e=>[...e].reduce(((e,_)=>(e<<5)-e+_.charCodeAt(0)),0),__md_get=(e,_=localStorage,t=__md_scope)=>JSON.parse(_.getItem(t.pathname+"."+e)),__md_set=(e,_,t=localStorage,a=__md_scope)=>{try{t.setItem(a.pathname+"."+e,JSON.stringify(_))}catch(e){}}</script></head> <body dir=ltr data-md-color-scheme=default data-md-color-primary=indigo data-md-color-accent=indigo> <input class=md-toggle data-md-toggle=drawer type=checkbox id=__drawer autocomplete=off> <input class=md-toggle data-md-toggle=search type=checkbox id=__search autocomplete=off> <label class=md-overlay for=__drawer></label> <div data-md-component=skip> <a href=#arbitrary-type-conversions class=md-skip> Skip to content </a> </div> <div data-md-component=announce> </div> <header class=md-header data-md-component=header> <nav class="md-header__inner md-grid" aria-label=Header> <a href=../.. title="JSON for Modern C++" class="md-header__button md-logo" aria-label="JSON for Modern C++" data-md-component=logo> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 8a3 3 0 0 0 3-3 3 3 0 0 0-3-3 3 3 0 0 0-3 3 3 3 0 0 0 3 3m0 3.54C9.64 9.35 6.5 8 3 8v11c3.5 0 6.64 1.35 9 3.54 2.36-2.19 5.5-3.54 9-3.54V8c-3.5 0-6.64 1.35-9 3.54"/></svg> </a> <label class="md-header__button md-icon" for=__drawer> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M3 6h18v2H3zm0 5h18v2H3zm0 5h18v2H3z"/></svg> </label> <div class=md-header__title data-md-component=header-title> <div class=md-header__ellipsis> <div class=md-header__topic> <span class=md-ellipsis> JSON for Modern C++ </span> </div> <div class=md-header__topic data-md-component=header-topic> <span class=md-ellipsis> Arbitrary Type Conversions </span> </div> </div> </div> <form class=md-header__option data-md-component=palette> <input class=md-option data-md-color-media="(prefers-color-scheme: light)" data-md-color-scheme=default data-md-color-primary=indigo data-md-color-accent=indigo aria-label="Switch to dark mode" type=radio name=__palette id=__palette_0> <label class="md-header__button md-icon" title="Switch to dark mode" for=__palette_1 hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 8a4 4 0 0 0-4 4 4 4 0 0 0 4 4 4 4 0 0 0 4-4 4 4 0 0 0-4-4m0 10a6 6 0 0 1-6-6 6 6 0 0 1 6-6 6 6 0 0 1 6 6 6 6 0 0 1-6 6m8-9.31V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12z"/></svg> </label> <input class=md-option data-md-color-media="(prefers-color-scheme: dark)" data-md-color-scheme=slate data-md-color-primary=indigo data-md-color-accent=indigo aria-label="Switch to light mode" type=radio name=__palette id=__palette_1> <label class="md-header__button md-icon" title="Switch to light mode" for=__palette_0 hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6a6 6 0 0 1 6 6 6 6 0 0 1-6 6m8-9.31V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12z"/></svg> </label> </form> <script>var palette=__md_get("__palette");if(palette&&palette.color){if("(prefers-color-scheme)"===palette.color.media){var media=matchMedia("(prefers-color-scheme: light)"),input=document.querySelector(media.matches?"[data-md-color-media='(prefers-color-scheme: light)']":"[data-md-color-media='(prefers-color-scheme: dark)']");palette.color.media=input.getAttribute("data-md-color-media"),palette.color.scheme=input.getAttribute("data-md-color-scheme"),palette.color.primary=input.getAttribute("data-md-color-primary"),palette.color.accent=input.getAttribute("data-md-color-accent")}for(var[key,value]of Object.entries(palette.color))document.body.setAttribute("data-md-color-"+key,value)}</script> <label class="md-header__button md-icon" for=__search> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M9.5 3A6.5 6.5 0 0 1 16 9.5c0 1.61-.59 3.09-1.56 4.23l.27.27h.79l5 5-1.5 1.5-5-5v-.79l-.27-.27A6.52 6.52 0 0 1 9.5 16 6.5 6.5 0 0 1 3 9.5 6.5 6.5 0 0 1 9.5 3m0 2C7 5 5 7 5 9.5S7 14 9.5 14 14 12 14 9.5 12 5 9.Line truncated
|
||||
<!doctype html><html lang=en class=no-js> <head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><meta name=description content="JSON for Modern C++ is a header-only C++11 library that makes JSON a first-class data type."><meta name=author content="Niels Lohmann"><link href="https://json.nlohmann.me/features/arbitrary_types/" rel="canonical"><link href=../ rel=prev><link href=../type_recipes/ rel=next><link rel=icon href=../../assets/images/favicon.png><meta name=generator content="mkdocs-1.6.1, mkdocs-material-9.7.7"><title>Arbitrary Type Conversions - JSON for Modern C++</title><link rel=stylesheet href=../../assets/stylesheets/main.ec1eaa64.min.css><link rel=stylesheet href=../../assets/stylesheets/palette.ab4e12ef.min.css><link rel=stylesheet href=../../css/custom.css><link rel=stylesheet href=../../css/brand.css><link rel=stylesheet href=../../css/fig-sax.css><link rel=stylesheet href=../../css/fig-jsonview.css><link rel=stylesheet href=../../css/fig-exceptions.css><link rel=stylesheet href=../../css/fig-pointer.css><link rel=stylesheet href=../../css/fig-charts.css><link rel=stylesheet href=../../css/fig-integration.css><link rel=stylesheet href=../../css/fig-macros.css><script>__md_scope=new URL("../..",location),__md_hash=e=>[...e].reduce(((e,_)=>(e<<5)-e+_.charCodeAt(0)),0),__md_get=(e,_=localStorage,t=__md_scope)=>JSON.parse(_.getItem(t.pathname+"."+e)),__md_set=(e,_,t=localStorage,a=__md_scope)=>{try{t.setItem(a.pathname+"."+e,JSON.stringify(_))}catch(e){}}</script></head> <body dir=ltr data-md-color-scheme=default data-md-color-primary=custom data-md-color-accent=custom> <input class=md-toggle data-md-toggle=drawer type=checkbox id=__drawer autocomplete=off> <input class=md-toggle data-md-toggle=search type=checkbox id=__search autocomplete=off> <label class=md-overlay for=__drawer></label> <div data-md-component=skip> <a href=#arbitrary-type-conversions class=md-skip> Skip to content </a> </div> <div data-md-component=announce> </div> <header class=md-header data-md-component=header> <nav class="md-header__inner md-grid" aria-label=Header> <a href=../.. title="JSON for Modern C++" class="md-header__button md-logo" aria-label="JSON for Modern C++" data-md-component=logo> <img src=../../images/wordmark-header.svg alt=logo> </a> <label class="md-header__button md-icon" for=__drawer> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M3 6h18v2H3zm0 5h18v2H3zm0 5h18v2H3z"/></svg> </label> <div class=md-header__title data-md-component=header-title> <div class=md-header__ellipsis> <div class=md-header__topic> <span class=md-ellipsis> JSON for Modern C++ </span> </div> <div class=md-header__topic data-md-component=header-topic> <span class=md-ellipsis> Arbitrary Type Conversions </span> </div> </div> </div> <form class=md-header__option data-md-component=palette> <input class=md-option data-md-color-media="(prefers-color-scheme: light)" data-md-color-scheme=default data-md-color-primary=custom data-md-color-accent=custom aria-label="Switch to dark mode" type=radio name=__palette id=__palette_0> <label class="md-header__button md-icon" title="Switch to dark mode" for=__palette_1 hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 8a4 4 0 0 0-4 4 4 4 0 0 0 4 4 4 4 0 0 0 4-4 4 4 0 0 0-4-4m0 10a6 6 0 0 1-6-6 6 6 0 0 1 6-6 6 6 0 0 1 6 6 6 6 0 0 1-6 6m8-9.31V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12z"/></svg> </label> <input class=md-option data-md-color-media="(prefers-color-scheme: dark)" data-md-color-scheme=slate data-md-color-primary=custom data-md-color-accent=custom aria-label="Switch to light mode" type=radio name=__palette id=__palette_1> <label class="md-header__button md-icon" title="Switch to light mode" for=__palette_0 hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6a6 6 0 0 1 6 6 6 6 0 0 1-6 6m8-9.31V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12z"/></svg> </label> </form> <script>var palette=__md_get("__palette");if(palette&&palette.color){if("(prefers-color-scheme)"===palette.color.media){var media=matchMedia("(prefers-color-scheme: light)"),input=document.querySelector(media.matches?"[data-md-color-media='(prefers-color-scheme: light)']":"[data-md-color-media='(prefers-color-scheme: dark)']");palette.color.media=input.getAttribute("data-md-color-media"),palette.color.scheme=input.getAttribute("data-md-color-scheme"),palette.color.primary=input.getAttribute("data-md-color-primary"),palette.color.accent=input.getAttribute("data-md-color-accent")}for(var[key,value]of Object.entries(palette.color))document.body.setAttribute("data-md-color-"+key,value)}</script> <label class="md-header__button md-icon" for=__search> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M9.5 3A6.5 6.5 0 0 1 16 9.5c0Line truncated
|
||||
<span class=w> </span><span class=c1>// a simple struct to model a person</span>
|
||||
<span class=w> </span><span class=k>struct</span><span class=w> </span><span class=nc>person</span><span class=w> </span><span class=p>{</span>
|
||||
<span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=w> </span><span class=n>name</span><span class=p>;</span>
|
||||
@@ -122,24 +122,24 @@
|
||||
<span class=p>}</span>
|
||||
</code></pre></div> <p>Output:</p> <div class=highlight><pre><span></span><code>Ned Flanders (60) lives in 744 Evergreen Terrace
|
||||
</code></pre></div> </details> <h2 id=simplify-your-life-with-macros>Simplify your life with macros<a class=headerlink href=#simplify-your-life-with-macros title="Permanent link">¶</a></h2> <p>If you just want to serialize/deserialize some structs, the <code>to_json</code>/<code>from_json</code> functions can be a lot of boilerplate.</p> <p>There are several macros to make your life easier as long as you want to use a <abbr title="JavaScript Object Notation">JSON</abbr> object as serialization. The macros are following the naming pattern, and you can choose the macro based on the needed features:</p> <ul> <li>All the macros start with <code>NLOHMANN_DEFINE</code>.</li> <li>If you want a macro for the derived object, use the <a href=../../api/macros/nlohmann_define_derived_type/ ><code>DERIVED_TYPE</code></a> variant, otherwise use <code>TYPE</code>.<ul> <li>The <code>DERIVED_TYPE</code> variant requires an additional parameter of a base type, which should have the <code>to_json</code>/<code>from_json</code> functions defined. For instance, with a macro of its own.</li> </ul> </li> <li>If you need access to the private fields use <a href=../../api/macros/nlohmann_define_type_intrusive/ ><code>INTRUSIVE</code></a> variant, otherwise use <a href=../../api/macros/nlohmann_define_type_non_intrusive/ ><code>NON_INTRUSIVE</code></a>.<ul> <li>The <code>INTRUSIVE</code> macro should be defined <strong>inside</strong> the target class/struct, <code>NON_INTRUSIVE</code> should be defined within the same namespace.</li> </ul> </li> <li>If you want to deserialize the incomplete JSONs, use the <code>WITH_DEFAULTS</code> variant, which will use the default values for the member variables absent in <abbr title="JavaScript Object Notation">JSON</abbr>, the variant without <code>WITH_DEFAULTS</code> will raise an exception.</li> <li>If you do not need deserialization at all and only interested in <code>to_json</code> function, you can use the <code>ONLY_SERIALIZE</code> variant.</li> <li>If you want to use the custom <abbr title="JavaScript Object Notation">JSON</abbr> names for member variables, use <a href=../../api/macros/nlohmann_define_type_with_names/ ><code>WITH_NAMES</code></a> variant, otherwise the <abbr title="JavaScript Object Notation">JSON</abbr> name of the variable will be the same as its regular name. </li> </ul> <p>For all the macros, the first parameter is the name of the class/struct. The <code>DERIVED_TYPE</code> macros require a second parameter of a base class. All the remaining parameters name the member variables. The <code>WITH_NAMES</code> macros require a <abbr title="JavaScript Object Notation">JSON</abbr> name before each of the variables.</p> <pre class=mermaid><code>flowchart TD
|
||||
A["choosing a NLOHMANN_DEFINE_* macro"] --> B{"adding fields to a base class?"}
|
||||
A["choosing a NLOHMANN_DEFINE_* macro"] --> B{{"adding fields to a base class?"}}
|
||||
B -->|"yes"| C["...DERIVED_TYPE..."]
|
||||
B -->|"no"| D["...TYPE..."]
|
||||
C --> E{"need access to private members?"}
|
||||
C --> E{{"need access to private members?"}}
|
||||
D --> E
|
||||
E -->|"yes"| F["...INTRUSIVE... (used inside the class)"]
|
||||
E -->|"no"| G["...NON_INTRUSIVE... (used in the namespace)"]
|
||||
F --> H{"only serializing, never parsing back?"}
|
||||
F --> H{{"only serializing, never parsing back?"}}
|
||||
G --> H
|
||||
H -->|"yes"| I["...ONLY_SERIALIZE"]
|
||||
H -->|"no"| J{"allow missing keys when parsing?"}
|
||||
H -->|"no"| J{{"allow missing keys when parsing?"}}
|
||||
J -->|"yes"| K["...WITH_DEFAULT"]
|
||||
J -->|"no"| L["plain (missing keys throw)"]
|
||||
I --> M{"need custom JSON key names?"}
|
||||
I --> M{{"need custom JSON key names?"}}
|
||||
K --> M
|
||||
L --> M
|
||||
M -->|"yes"| N["...WITH_NAMES"]
|
||||
M -->|"no"| O["done"]</code></pre> <table> <thead> <tr> <th>Need access to private members</th> <th>Need only serialization</th> <th>Allow missing values when de-serializing</th> <th>macro</th> </tr> </thead> <tbody> <tr> <td><div style="color: green;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m16.28-2.72a.75.75 0 0 0-.018-1.042.75.75 0 0 0-1.042-.018l-5.97 5.97-2.47-2.47a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042l3 3a.75.75 0 0 0 1.06 0Z"/></svg></span></div></td> <td><div style="color: red;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m8.036-4.024a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042L10.939 12l-2.963 2.963a.749.749 0 0 0 .326 1.275.75.75 0 0 0 .734-.215L12 13.06l2.963 2.964a.75.75 0 0 0 1.061-1.06L13.061 12l2.963-2.964a.749.749 0 0 0-.326-1.275.75.75 0 0 0-.734.215L12 10.939Z"/></svg></span></div></td> <td><div style="color: red;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m8.036-4.024a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042L10.939 12l-2.963 2.963a.749.749 0 0 0 .326 1.275.75.75 0 0 0 .734-.215L12 13.06l2.963 2.964a.75.75 0 0 0 1.061-1.06L13.061 12l2.963-2.964a.749.749 0 0 0-.326-1.275.75.75 0 0 0-.734.215L12 10.939Z"/></svg></span></div></td> <td><a href=../../api/macros/nlohmann_define_type_intrusive/ ><strong>NLOHMANN_DEFINE_TYPE_INTRUSIVE</strong></a></td> </tr> <tr> <td><div style="color: green;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m16.28-2.72a.75.75 0 0 0-.018-1.042.75.75 0 0 0-1.042-.018l-5.97 5.97-2.47-2.47a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042l3 3a.75.75 0 0 0 1.06 0Z"/></svg></span></div></td> <td><div style="color: red;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m8.036-4.024a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042L10.939 12l-2.963 2.963a.749.749 0 0 0 .326 1.275.75.75 0 0 0 .734-.215L12 13.06l2.963 2.964a.75.75 0 0 0 1.061-1.06L13.061 12l2.963-2.964a.749.749 0 0 0-.326-1.275.75.75 0 0 0-.734.215L12 10.939Z"/></svg></span></div></td> <td><div style="color: green;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m16.28-2.72a.75.75 0 0 0-.018-1.042.75.75 0 0 0-1.042-.018l-5.97 5.97-2.47-2.47a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042l3 3a.75.75 0 0 0 1.06 0Z"/></svg></span></div></td> <td><a href=../../api/macros/nlohmann_define_type_intrusive/ ><strong>NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT</strong></a></td> </tr> <tr> <td><div style="color: green;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m16.28-2.72a.75.75 0 0 0-.018-1.042.75.75 0 0 0-1.042-.018l-5.97 5.97-2.47-2.47a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042l3 3a.75.75 0 0 0 1.06 0Z"/></svg></span></div></td> <td><div style="color: green;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m16.28-2.72a.75.75 0 0 0-.018-1.042.75.75 0 0 0-1.042-.018l-5.97 5.97-2.47-2.47a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042l3 3a.75.75 0 0 0 1.06 0Z"/></svg></span></div></td> <td><div style="color: grey;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m16.333-4.167a.825.825 0 0 0-1.166-1.166l-9.5 9.5a.825.825 0 0 0 1.166 1.166Z"/></svg></span></div></td> <td><a href=../../api/macros/nlohmann_define_type_intrusive/ ><strong>NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE</strong></a></td> </tr> <tr> <td><div style="color: red;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m8.036-4.024a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042L10.939 12l-2.963 2.963a.749.749 0 0 0 .326 1.275.75.75 0 0 0 .734-.215L12 13.06l2.963 2.964a.75.75 0 0 0 1.061-1.06L13.061 12l2.963-2.964a.749.749 0 0 0-.326-1.275.75.75 0 0 0-.734.215L12 10.939Z"/></svg></span></div></td> <td><div style="color: red;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m8.036-4.024a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042L10.939 12l-2.963 2.963a.749.749 0 0 0 .326 1.275.75.75 0 0 0 .734-.215L12 13.06l2.963 2.964a.75.75 0 0 0 1.061-1.Line truncated
|
||||
M -->|"no"| O["done"]</code></pre> <p class=nj-caption>Decision tree for choosing a <code>NLOHMANN_DEFINE_*</code> macro: answer the questions from top to bottom; each answer picks one part of the macro name, and the parts are combined in this order. The table below lists the resulting macros.</p> <table> <thead> <tr> <th>Need access to private members</th> <th>Need only serialization</th> <th>Allow missing values when de-serializing</th> <th>macro</th> </tr> </thead> <tbody> <tr> <td><div style="color: green;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m16.28-2.72a.75.75 0 0 0-.018-1.042.75.75 0 0 0-1.042-.018l-5.97 5.97-2.47-2.47a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042l3 3a.75.75 0 0 0 1.06 0Z"/></svg></span></div></td> <td><div style="color: red;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m8.036-4.024a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042L10.939 12l-2.963 2.963a.749.749 0 0 0 .326 1.275.75.75 0 0 0 .734-.215L12 13.06l2.963 2.964a.75.75 0 0 0 1.061-1.06L13.061 12l2.963-2.964a.749.749 0 0 0-.326-1.275.75.75 0 0 0-.734.215L12 10.939Z"/></svg></span></div></td> <td><div style="color: red;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m8.036-4.024a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042L10.939 12l-2.963 2.963a.749.749 0 0 0 .326 1.275.75.75 0 0 0 .734-.215L12 13.06l2.963 2.964a.75.75 0 0 0 1.061-1.06L13.061 12l2.963-2.964a.749.749 0 0 0-.326-1.275.75.75 0 0 0-.734.215L12 10.939Z"/></svg></span></div></td> <td><a href=../../api/macros/nlohmann_define_type_intrusive/ ><strong>NLOHMANN_DEFINE_TYPE_INTRUSIVE</strong></a></td> </tr> <tr> <td><div style="color: green;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m16.28-2.72a.75.75 0 0 0-.018-1.042.75.75 0 0 0-1.042-.018l-5.97 5.97-2.47-2.47a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042l3 3a.75.75 0 0 0 1.06 0Z"/></svg></span></div></td> <td><div style="color: red;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m8.036-4.024a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042L10.939 12l-2.963 2.963a.749.749 0 0 0 .326 1.275.75.75 0 0 0 .734-.215L12 13.06l2.963 2.964a.75.75 0 0 0 1.061-1.06L13.061 12l2.963-2.964a.749.749 0 0 0-.326-1.275.75.75 0 0 0-.734.215L12 10.939Z"/></svg></span></div></td> <td><div style="color: green;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m16.28-2.72a.75.75 0 0 0-.018-1.042.75.75 0 0 0-1.042-.018l-5.97 5.97-2.47-2.47a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042l3 3a.75.75 0 0 0 1.06 0Z"/></svg></span></div></td> <td><a href=../../api/macros/nlohmann_define_type_intrusive/ ><strong>NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT</strong></a></td> </tr> <tr> <td><div style="color: green;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m16.28-2.72a.75.75 0 0 0-.018-1.042.75.75 0 0 0-1.042-.018l-5.97 5.97-2.47-2.47a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042l3 3a.75.75 0 0 0 1.06 0Z"/></svg></span></div></td> <td><div style="color: green;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m16.28-2.72a.75.75 0 0 0-.018-1.042.75.75 0 0 0-1.042-.018l-5.97 5.97-2.47-2.47a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042l3 3a.75.75 0 0 0 1.06 0Z"/></svg></span></div></td> <td><div style="color: grey;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m16.333-4.167a.825.825 0 0 0-1.166-1.166l-9.5 9.5a.825.825 0 0 0 1.166 1.166Z"/></svg></span></div></td> <td><a href=../../api/macros/nlohmann_define_type_intrusive/ ><strong>NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE</strong></a></td> </tr> <tr> <td><div style="color: red;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12m8.036-4.024a.75.75 0 0 0-1.042.018.75.75 0 0 0-.018 1.042L10.939 12l-2.963 2.963a.749.749 0 0 0 .326 1.275.75.75 0 0 0 .734-.215L12 13.06l2.963 2.964a.75.75 0 0 0 1.061-1.06L13.061 12l2.963-2.964a.749.749 0 0 0-.326-1.275.75.75 0 0 0-.734.215L12 10.939Z"/></svg></span></div></td> <td><div style="color: red;"><span class=twemoji><svg xmlns=http://www.w3.org/2000/svg viewboxLine truncated
|
||||
<span class=w> </span><span class=n>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE</span><span class=p>(</span><span class=n>person</span><span class=p>,</span><span class=w> </span><span class=n>name</span><span class=p>,</span><span class=w> </span><span class=n>address</span><span class=p>,</span><span class=w> </span><span class=n>age</span><span class=p>)</span>
|
||||
<span class=p>}</span>
|
||||
</code></pre></div> <p>If you want to inherit the <code>person</code> struct and add a field to it, it can be done with:</p> <div class=highlight><pre><span></span><code><span class=k>namespace</span><span class=w> </span><span class=nn>ns</span><span class=w> </span><span class=p>{</span>
|
||||
@@ -173,7 +173,7 @@
|
||||
<span class=w> </span><span class=s>"postcode"</span><span class=p>,</span><span class=w> </span><span class=n>m_postcode</span><span class=p>)</span>
|
||||
<span class=w> </span><span class=p>};</span>
|
||||
<span class=p>}</span>
|
||||
</code></pre></div> </details> <div class="admonition warning"> <p class=admonition-title>Overriding conversions for natively-supported types</p> <p>The library already provides built-in <code>to_json</code>/<code>from_json</code> conversions for <abbr title="Standard Template Library">STL</abbr> containers such as <code>std::vector</code>, <code>std::array</code>, and <code>std::map</code>. Defining your own free-function <code>to_json</code>/<code>from_json</code> overload for one of these container types directly (instead of for your own type) can conflict with the built-in overload during overload resolution, producing compiler errors ("no matching overloaded function", "call is ambiguous") that vary by compiler and library version. If you need different conversion behavior for a container type the library already handles, wrap it in your own type (or use <code>adl_serializer</code> specialization, as shown <a href=#how-do-i-convert-third-party-types>above</a> for <code>boost::optional</code>) instead of trying to re-specialize <code>to_json</code>/<code>from_json</code> for the container type itself.</p> </div> <div class="admonition warning"> <p class=admonition-title>Raw C-style arrays</p> <p>Members declared as raw C-style arrays (e.g., <code>char buf[1024]</code>) do not round-trip safely through <code>NLOHMANN_DEFINE_TYPE_*</code> macros or the default (de)serializers: <code>to_json</code> serializes any <code>char</code> array as a <abbr title="JavaScript Object Notation">JSON</abbr> <em>string</em> (matching the <code>std::string</code>-constructible overload), but the <code>from_json</code> overload for fixed-size arrays expects a <abbr title="JavaScript Object Notation">JSON</abbr> <em>array</em> and iterates it element-wise, which fails with a <code>type_error</code> when given a string. Use <code>std::string</code>, <code>std::array<char, N></code>, or a manually written <code>to_json</code>/<code>from_json</code> pair for such members instead.</p> </div> <div class="admonition note"> <p class=admonition-title>Macros and <code>nlohmann::ordered_json</code></p> <p>The <code>NLOHMANN_DEFINE_TYPE_*</code>/<code>NLOHMANN_DEFINE_DERIVED_TYPE_*</code> macros are generic over any <code>basic_json</code> specialization, including <code>nlohmann::ordered_json</code>. Simply use <code>ordered_json</code> as the target type and members are serialized in declaration order -- no separate macro or extra code is needed.</p> <div class=highlight><pre><span></span><code><span class=k>namespace</span><span class=w> </span><span class=nn>ns</span><span class=w> </span><span class=p>{</span>
|
||||
</code></pre></div> </details> <div class="admonition warning"> <p class=admonition-title>Overriding conversions for natively-supported types</p> <p>The library already provides built-in <code>to_json</code>/<code>from_json</code> conversions for <abbr title="Standard Template Library">STL</abbr> containers such as <code>std::vector</code>, <code>std::array</code>, and <code>std::map</code>. Defining your own free-function <code>to_json</code>/<code>from_json</code> overload for one of these container types directly (instead of for your own type) can conflict with the built-in overload during overload resolution, producing compiler errors ("no matching overloaded function", "call is ambiguous") that vary by compiler and library version. If you need different conversion behavior for a container type the library already handles, wrap it in your own type (or use <code>adl_serializer</code> specialization, as shown <a href=#how-do-i-convert-third-party-types>above</a> for <code>boost::optional</code>) instead of trying to re-specialize <code>to_json</code>/<code>from_json</code> for the container type itself.</p> </div> <div class="admonition warning"> <p class=admonition-title>Raw C-style arrays</p> <p>Members declared as raw C-style arrays (e.g., <code>char buf[1024]</code>) do not round-trip safely through <code>NLOHMANN_DEFINE_TYPE_*</code> macros or the default (de)serializers: <code>to_json</code> serializes any <code>char</code> array as a <abbr title="JavaScript Object Notation">JSON</abbr> <em>string</em> (matching the <code>std::string</code>-constructible overload), but the <code>from_json</code> overload for fixed-size arrays expects a <abbr title="JavaScript Object Notation">JSON</abbr> <em>array</em> and iterates it element-wise, which fails with a <code>type_error</code> when given a string. Use <code>std::string</code>, <code>std::array<char, N></code>, or a manually written <code>to_json</code>/<code>from_json</code> pair for such members instead.</p> </div> <div class="admonition note"> <p class=admonition-title>Macros and <code>nlohmann::ordered_json</code></p> <p>The <code>NLOHMANN_DEFINE_TYPE_*</code>/<code>NLOHMANN_DEFINE_DERIVED_TYPE_*</code> macros are generic over any <code>basic_json</code> specialization, including <code>nlohmann::ordered_json</code>. Simply use <code>ordered_json</code> as the target type and members are serialized in declaration order — no separate macro or extra code is needed.</p> <div class=highlight><pre><span></span><code><span class=k>namespace</span><span class=w> </span><span class=nn>ns</span><span class=w> </span><span class=p>{</span>
|
||||
<span class=w> </span><span class=n>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE</span><span class=p>(</span><span class=n>person</span><span class=p>,</span><span class=w> </span><span class=n>name</span><span class=p>,</span><span class=w> </span><span class=n>address</span><span class=p>,</span><span class=w> </span><span class=n>age</span><span class=p>)</span>
|
||||
<span class=p>}</span>
|
||||
|
||||
@@ -188,11 +188,11 @@
|
||||
|
||||
<span class=n>ns</span><span class=o>::</span><span class=n>marker</span><span class=w> </span><span class=n>m</span><span class=p>{};</span>
|
||||
<span class=n>nlohmann</span><span class=o>::</span><span class=n>json</span><span class=w> </span><span class=n>j</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>m</span><span class=p>;</span><span class=w> </span><span class=c1>// {}</span>
|
||||
</code></pre></div> </div> <div class="admonition note"> <p class=admonition-title>No macro for non-default-constructible types</p> <p>There is currently no <code>NLOHMANN_DEFINE_TYPE_*</code>-style macro for types that are not <a href="https://en.cppreference.com/w/cpp/named_req/DefaultConstructible">DefaultConstructible</a>. This is not an intentional omission of documentation -- no such macro exists yet; see <a href=#how-can-i-use-get-for-non-default-constructiblenon-copyable-types>How can I use <code>get()</code> for non-default constructible/non-copyable types?</a> for the manual pattern to use instead.</p> </div> <h2 id=how-do-i-convert-third-party-types>How do I convert third-party types?<a class=headerlink href=#how-do-i-convert-third-party-types title="Permanent link">¶</a></h2> <p>This requires a bit more advanced technique. But first, let us see how this conversion mechanism works:</p> <pre class=mermaid><code>flowchart LR
|
||||
</code></pre></div> </div> <div class="admonition note"> <p class=admonition-title>No macro for non-default-constructible types</p> <p>There is currently no <code>NLOHMANN_DEFINE_TYPE_*</code>-style macro for types that are not <a href="https://en.cppreference.com/w/cpp/named_req/DefaultConstructible">DefaultConstructible</a>. This is not an intentional omission of documentation — no such macro exists yet; see <a href=#how-can-i-use-get-for-non-default-constructiblenon-copyable-types>How can I use <code>get()</code> for non-default constructible/non-copyable types?</a> for the manual pattern to use instead.</p> </div> <h2 id=how-do-i-convert-third-party-types>How do I convert third-party types?<a class=headerlink href=#how-do-i-convert-third-party-types title="Permanent link">¶</a></h2> <p>This requires a bit more advanced technique. But first, let us see how this conversion mechanism works:</p> <pre class=mermaid><code>flowchart LR
|
||||
A["construct json j = t, or call j.get() for T"] --> B["JSONSerializer for T: to_json / from_json"]
|
||||
B -->|"default JSONSerializer"| C["adl_serializer for T: to_json / from_json"]
|
||||
C -->|"unqualified call, found via ADL"| D["free to_json(j, t) / from_json(j, t) in T's namespace"]
|
||||
B -->|"user specialization replaces the default"| E["user's adl_serializer specialization for T"]</code></pre> <p>The library uses <strong><abbr title="JavaScript Object Notation">JSON</abbr> Serializers</strong> to convert types to <abbr title="JavaScript Object Notation">JSON</abbr>. The default serializer for <code>nlohmann::json</code> is <code>nlohmann::adl_serializer</code> (<abbr title="Argument-dependent lookup">ADL</abbr> means <a href="https://en.cppreference.com/w/cpp/language/adl">Argument-Dependent Lookup</a>).</p> <p>It is implemented like this (simplified):</p> <div class=highlight><pre><span></span><code><span class=k>template</span><span class=w> </span><span class=o><</span><span class=k>typename</span><span class=w> </span><span class=nc>T</span><span class=o>></span>
|
||||
B -->|"user specialization replaces the default"| E["user's adl_serializer specialization for T"]</code></pre> <p class=nj-caption>How a conversion between <code>json</code> and a type <code>T</code> is dispatched: the default <code>adl_serializer</code> calls the free <code>to_json</code>/<code>from_json</code> functions found by argument-dependent lookup, while a user specialization of <code>adl_serializer</code> replaces this path.</p> <p>The library uses <strong><abbr title="JavaScript Object Notation">JSON</abbr> Serializers</strong> to convert types to <abbr title="JavaScript Object Notation">JSON</abbr>. The default serializer for <code>nlohmann::json</code> is <code>nlohmann::adl_serializer</code> (<abbr title="Argument-dependent lookup">ADL</abbr> means <a href="https://en.cppreference.com/w/cpp/language/adl">Argument-Dependent Lookup</a>).</p> <p>It is implemented like this (simplified):</p> <div class=highlight><pre><span></span><code><span class=k>template</span><span class=w> </span><span class=o><</span><span class=k>typename</span><span class=w> </span><span class=nc>T</span><span class=o>></span>
|
||||
<span class=k>struct</span><span class=w> </span><span class=nc>adl_serializer</span><span class=w> </span><span class=p>{</span>
|
||||
<span class=w> </span><span class=k>static</span><span class=w> </span><span class=kt>void</span><span class=w> </span><span class=nf>to_json</span><span class=p>(</span><span class=n>json</span><span class=o>&</span><span class=w> </span><span class=n>j</span><span class=p>,</span><span class=w> </span><span class=k>const</span><span class=w> </span><span class=n>T</span><span class=o>&</span><span class=w> </span><span class=n>value</span><span class=p>)</span><span class=w> </span><span class=p>{</span>
|
||||
<span class=w> </span><span class=c1>// calls the "to_json" method in T's namespace</span>
|
||||
@@ -305,7 +305,7 @@
|
||||
<span class=w> </span><span class=p>}</span>
|
||||
<span class=w> </span><span class=p>};</span>
|
||||
<span class=p>}</span>
|
||||
</code></pre></div> <h2 id=why-isnt-my-to_json-or-from_json-found>Why isn't my <code>to_json</code> or <code>from_json</code> found?<a class=headerlink href=#why-isnt-my-to_json-or-from_json-found title="Permanent link">¶</a></h2> <p>The library calls <code>to_json</code> and <code>from_json</code> without qualification, so the compiler finds them by <a href="https://en.cppreference.com/w/cpp/language/adl">argument-dependent lookup</a> in the namespace of the type, or in the namespaces of its template arguments. The usual reasons for a function that is "not found" are:</p> <ul> <li><strong>The type is an alias of a standard type.</strong> After <code class=highlight><span class=k>using</span><span class=w> </span><span class=n>Hash</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>array</span><span class=o><</span><span class=n>std</span><span class=o>::</span><span class=kt>uint8_t</span><span class=p>,</span><span class=w> </span><span class=mi>6</span><span class=o>></span><span class=p>;</span></code> the type <em>is</em> <code>std::array<std::uint8_t, 6></code>, which lives in namespace <code>std</code>. A <code>to_json(json&, const Hash&)</code> in your namespace is never selected. Either give the type its own identity, for example <code class=highlight><span class=k>struct</span><span class=w> </span><span class=nc>Hash</span><span class=w> </span><span class=o>:</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>array</span><span class=o><</span><span class=n>std</span><span class=o>::</span><span class=kt>uint8_t</span><span class=p>,</span><span class=w> </span><span class=mi>6</span><span class=o>></span><span class=w> </span><span class=p>{};</span></code> (the function is then found in <code>Hash</code>'s namespace), or specialize <a href=#how-do-i-convert-third-party-types><code>adl_serializer<Hash></code></a>.</li> <li><strong>The function is in the wrong namespace.</strong> It must be in the namespace of the type (a global type needs a global function), not in the namespace of the code that calls the conversion. Specializations of <code>adl_serializer</code> belong in namespace <code>nlohmann</code>.</li> <li><strong>It is declared too late.</strong> A conversion can only use what has been declared when it is instantiated. If <code class=highlight><span class=n>json</span><span class=w> </span><span class=n>j</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>vector</span><span class=o><</span><span class=n>third_party</span><span class=o>::</span><span class=n>string</span><span class=o>></span><span class=p>{...};</span></code> appears before the <code>adl_serializer</code> specialization, the compiler reports an error such as "explicit specialization of <code>adl_serializer<...></code> after instantiation". Put the specialization in a small header that every file includes <strong>before</strong> it uses the type with <code>json</code>.</li> <li><strong>It is a template.</strong> For <code>template <class T> struct box</code>, write <code>template <class T> void to_json(json&, const box<T>&)</code>, not an overload for one <code>T</code>.</li> <li><strong>It worked by accident.</strong> Some versions found <code>to_json</code> overloads in <code>nlohmann::detail</code> through argument-dependent lookup of the base class of <code>basic_json</code>. Do not rely on this; it is not part of the interface.</li> </ul> <p>For smart pointers, class hierarchies, <code>std::variant</code>, and <code>std::chrono</code>, see <a href=../type_recipes/ >Recipes for common types</a>.</p> <h2 id=why-cant-i-convert-tofrom-stdany>Why can't I convert to/from <code>std::any</code>?<a class=headerlink href=#why-cant-i-convert-tofrom-stdany title="Permanent link">¶</a></h2> <p><code>std::any</code> is intentionally excluded from <code>get<T>()</code>/generic conversion support, so <code>get<std::any>()</code> and containers like <code>std::map<std::string, std::any></code> fail to compile by design -- there is no way to know, from a <code>json</code> value alone, which concrete type to store inside the <code>std::any</code>. To work with heterogeneous <abbr title="JavaScript Object Notation">JSON</abbr> values, dispatch on the value's type manually and construct the <code>std::any</code> (or extract from it) yourself:</p> <div class=highlight><pre><span></span><code><span class=n>std</span><span class=o>::</span><span class=n>any</span><span class=w> </span><span class=nf>value_to_any</span><span class=p>(</span><span class=k>const</span><span class=w> </span><span class=n>json</span><span class=o>&</span><span class=w> </span><span class=n>j</span><span class=p>)</span><span class=w> </span><span class=p>{</spanLine truncated
|
||||
</code></pre></div> <h2 id=why-isnt-my-to_json-or-from_json-found>Why isn't my <code>to_json</code> or <code>from_json</code> found?<a class=headerlink href=#why-isnt-my-to_json-or-from_json-found title="Permanent link">¶</a></h2> <p>The library calls <code>to_json</code> and <code>from_json</code> without qualification, so the compiler finds them by <a href="https://en.cppreference.com/w/cpp/language/adl">argument-dependent lookup</a> in the namespace of the type, or in the namespaces of its template arguments. The usual reasons for a function that is "not found" are:</p> <ul> <li><strong>The type is an alias of a standard type.</strong> After <code class=highlight><span class=k>using</span><span class=w> </span><span class=n>Hash</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>array</span><span class=o><</span><span class=n>std</span><span class=o>::</span><span class=kt>uint8_t</span><span class=p>,</span><span class=w> </span><span class=mi>6</span><span class=o>></span><span class=p>;</span></code> the type <em>is</em> <code>std::array<std::uint8_t, 6></code>, which lives in namespace <code>std</code>. A <code>to_json(json&, const Hash&)</code> in your namespace is never selected. Either give the type its own identity, for example <code class=highlight><span class=k>struct</span><span class=w> </span><span class=nc>Hash</span><span class=w> </span><span class=o>:</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>array</span><span class=o><</span><span class=n>std</span><span class=o>::</span><span class=kt>uint8_t</span><span class=p>,</span><span class=w> </span><span class=mi>6</span><span class=o>></span><span class=w> </span><span class=p>{};</span></code> (the function is then found in <code>Hash</code>'s namespace), or specialize <a href=#how-do-i-convert-third-party-types><code>adl_serializer<Hash></code></a>.</li> <li><strong>The function is in the wrong namespace.</strong> It must be in the namespace of the type (a global type needs a global function), not in the namespace of the code that calls the conversion. Specializations of <code>adl_serializer</code> belong in namespace <code>nlohmann</code>.</li> <li><strong>It is declared too late.</strong> A conversion can only use what has been declared when it is instantiated. If <code class=highlight><span class=n>json</span><span class=w> </span><span class=n>j</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>vector</span><span class=o><</span><span class=n>third_party</span><span class=o>::</span><span class=n>string</span><span class=o>></span><span class=p>{...};</span></code> appears before the <code>adl_serializer</code> specialization, the compiler reports an error such as "explicit specialization of <code>adl_serializer<...></code> after instantiation". Put the specialization in a small header that every file includes <strong>before</strong> it uses the type with <code>json</code>.</li> <li><strong>It is a template.</strong> For <code>template <class T> struct box</code>, write <code>template <class T> void to_json(json&, const box<T>&)</code>, not an overload for one <code>T</code>.</li> <li><strong>It worked by accident.</strong> Some versions found <code>to_json</code> overloads in <code>nlohmann::detail</code> through argument-dependent lookup of the base class of <code>basic_json</code>. Do not rely on this; it is not part of the interface.</li> </ul> <p>For smart pointers, class hierarchies, <code>std::variant</code>, and <code>std::chrono</code>, see <a href=../type_recipes/ >Recipes for common types</a>.</p> <h2 id=why-cant-i-convert-tofrom-stdany>Why can't I convert to/from <code>std::any</code>?<a class=headerlink href=#why-cant-i-convert-tofrom-stdany title="Permanent link">¶</a></h2> <p><code>std::any</code> is intentionally excluded from <code>get<T>()</code>/generic conversion support, so <code>get<std::any>()</code> and containers like <code>std::map<std::string, std::any></code> fail to compile by design — there is no way to know, from a <code>json</code> value alone, which concrete type to store inside the <code>std::any</code>. To work with heterogeneous <abbr title="JavaScript Object Notation">JSON</abbr> values, dispatch on the value's type manually and construct the <code>std::any</code> (or extract from it) yourself:</p> <div class=highlight><pre><span></span><code><span class=n>std</span><span class=o>::</span><span class=n>any</span><span class=w> </span><span class=nf>value_to_any</span><span class=p>(</span><span class=k>const</span><span class=w> </span><span class=n>json</span><span class=o>&</span><span class=w> </span><span class=n>j</span><span class=p>)</span><span class=w> </span><span class=p>{</spaLine truncated
|
||||
<span class=w> </span><span class=k>if</span><span class=w> </span><span class=p>(</span><span class=n>j</span><span class=p>.</span><span class=n>is_boolean</span><span class=p>())</span><span class=w> </span><span class=p>{</span><span class=w> </span><span class=k>return</span><span class=w> </span><span class=n>j</span><span class=p>.</span><span class=n>get</span><span class=o><</span><span class=kt>bool</span><span class=o>></span><span class=p>();</span><span class=w> </span><span class=p>}</span>
|
||||
<span class=w> </span><span class=k>if</span><span class=w> </span><span class=p>(</span><span class=n>j</span><span class=p>.</span><span class=n>is_number_integer</span><span class=p>())</span><span class=w> </span><span class=p>{</span><span class=w> </span><span class=k>return</span><span class=w> </span><span class=n>j</span><span class=p>.</span><span class=n>get</span><span class=o><</span><span class=kt>int</span><span class=o>></span><span class=p>();</span><span class=w> </span><span class=p>}</span>
|
||||
<span class=w> </span><span class=k>if</span><span class=w> </span><span class=p>(</span><span class=n>j</span><span class=p>.</span><span class=n>is_number_float</span><span class=p>())</span><span class=w> </span><span class=p>{</span><span class=w> </span><span class=k>return</span><span class=w> </span><span class=n>j</span><span class=p>.</span><span class=n>get</span><span class=o><</span><span class=kt>double</span><span class=o>></span><span class=p>();</span><span class=w> </span><span class=p>}</span>
|
||||
@@ -321,7 +321,7 @@
|
||||
<span class=w> </span><span class=k>if</span><span class=w> </span><span class=p>(</span><span class=n>a</span><span class=p>.</span><span class=n>type</span><span class=p>()</span><span class=w> </span><span class=o>==</span><span class=w> </span><span class=k>typeid</span><span class=p>(</span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=p>))</span><span class=w> </span><span class=p>{</span><span class=w> </span><span class=k>return</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>any_cast</span><span class=o><</span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=o>></span><span class=p>(</span><span class=n>a</span><span class=p>);</span><span class=w> </span><span class=p>}</span>
|
||||
<span class=w> </span><span class=k>return</span><span class=w> </span><span class=nb>nullptr</span><span class=p>;</span>
|
||||
<span class=p>}</span>
|
||||
</code></pre></div> <h2 id=why-does-serializing-a-stdmapstdunordered_map-with-non-string-keys-produce-an-array>Why does serializing a <code>std::map</code>/<code>std::unordered_map</code> with non-string keys produce an array?<a class=headerlink href=#why-does-serializing-a-stdmapstdunordered_map-with-non-string-keys-produce-an-array title="Permanent link">¶</a></h2> <p>A <code>std::map</code>/<code>std::unordered_map</code> whose key type is not string-like (e.g., <code>std::map<int, std::string></code>) cannot be serialized as a <abbr title="JavaScript Object Notation">JSON</abbr> object, because <abbr title="JavaScript Object Notation">JSON</abbr> object keys must be strings. See <a href=../types/#converting-maps-with-non-string-keys>Converting maps with non-string keys</a> in the types article for what the library does instead.</p> <h2 id=why-does-stdwstring-convert-or-dump-incorrectly>Why does <code>std::wstring</code> convert or dump incorrectly?<a class=headerlink href=#why-does-stdwstring-convert-or-dump-incorrectly title="Permanent link">¶</a></h2> <p>The library assumes <abbr title="Unicode Transformation Format">UTF</abbr>-8 encoding internally, so <code>std::wstring</code> is not supported out of the box -- see the <abbr title="Frequently Asked Questions">FAQ</abbr> entry on <a href=../../home/faq/#wide-string-handling>wide string handling</a> for why, and for a <abbr title="Unicode Transformation Format">UTF</abbr>-8 conversion recipe.</p> <h2 id=can-i-write-my-own-serializer-advanced-use>Can I write my own serializer? (Advanced use)<a class=headerlink href=#can-i-write-my-own-serializer-advanced-use title="Permanent link">¶</a></h2> <p>Yes. You might want to take a look at <a href="https://github.com/nlohmann/json/blob/develop/tests/src/unit-udt.cpp"><code>unit-udt.cpp</code></a> in the test suite, to see a few examples.</p> <p>If you write your own serializer, you will need to do a few things:</p> <ul> <li>use a different <code>basic_json</code> alias than <code>nlohmann::json</code> (the last template parameter of <code>basic_json</code> is the <code>JSONSerializer</code>)</li> <li>use your <code>basic_json</code> alias (or a template parameter) in all your <code>to_json</code>/<code>from_json</code> methods</li> <li>use <code>nlohmann::to_json</code> and <code>nlohmann::from_json</code> when you need <abbr title="Argument-dependent lookup">ADL</abbr></li> </ul> <p>Here is an example, without simplifications, that only accepts types with a size <= 32, and uses <abbr title="Argument-dependent lookup">ADL</abbr>.</p> <div class=highlight><pre><span></span><code><span class=c1>// You should use void as a second template argument</span>
|
||||
</code></pre></div> <h2 id=why-does-serializing-a-stdmapstdunordered_map-with-non-string-keys-produce-an-array>Why does serializing a <code>std::map</code>/<code>std::unordered_map</code> with non-string keys produce an array?<a class=headerlink href=#why-does-serializing-a-stdmapstdunordered_map-with-non-string-keys-produce-an-array title="Permanent link">¶</a></h2> <p>A <code>std::map</code>/<code>std::unordered_map</code> whose key type is not string-like (e.g., <code>std::map<int, std::string></code>) cannot be serialized as a <abbr title="JavaScript Object Notation">JSON</abbr> object, because <abbr title="JavaScript Object Notation">JSON</abbr> object keys must be strings. See <a href=../types/#converting-maps-with-non-string-keys>Converting maps with non-string keys</a> in the types article for what the library does instead.</p> <h2 id=why-does-stdwstring-convert-or-dump-incorrectly>Why does <code>std::wstring</code> convert or dump incorrectly?<a class=headerlink href=#why-does-stdwstring-convert-or-dump-incorrectly title="Permanent link">¶</a></h2> <p>The library assumes <abbr title="Unicode Transformation Format">UTF</abbr>-8 encoding internally, so <code>std::wstring</code> is not supported out of the box — see the <abbr title="Frequently Asked Questions">FAQ</abbr> entry on <a href=../../home/faq/#wide-string-handling>wide string handling</a> for why, and for a <abbr title="Unicode Transformation Format">UTF</abbr>-8 conversion recipe.</p> <h2 id=can-i-write-my-own-serializer-advanced-use>Can I write my own serializer? (Advanced use)<a class=headerlink href=#can-i-write-my-own-serializer-advanced-use title="Permanent link">¶</a></h2> <p>Yes. You might want to take a look at <a href="https://github.com/nlohmann/json/blob/develop/tests/src/unit-udt.cpp"><code>unit-udt.cpp</code></a> in the test suite, to see a few examples.</p> <p>If you write your own serializer, you will need to do a few things:</p> <ul> <li>use a different <code>basic_json</code> alias than <code>nlohmann::json</code> (the last template parameter of <code>basic_json</code> is the <code>JSONSerializer</code>)</li> <li>use your <code>basic_json</code> alias (or a template parameter) in all your <code>to_json</code>/<code>from_json</code> methods</li> <li>use <code>nlohmann::to_json</code> and <code>nlohmann::from_json</code> when you need <abbr title="Argument-dependent lookup">ADL</abbr></li> </ul> <p>Here is an example, without simplifications, that only accepts types with a size <= 32, and uses <abbr title="Argument-dependent lookup">ADL</abbr>.</p> <div class=highlight><pre><span></span><code><span class=c1>// You should use void as a second template argument</span>
|
||||
<span class=c1>// if you don't need compile-time checks on T</span>
|
||||
<span class=k>template</span><span class=o><</span><span class=k>typename</span><span class=w> </span><span class=nc>T</span><span class=p>,</span><span class=w> </span><span class=k>typename</span><span class=w> </span><span class=nc>SFINAE</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=k>typename</span><span class=w> </span><span class=nc>std</span><span class=o>::</span><span class=n>enable_if</span><span class=o><</span><span class=k>sizeof</span><span class=p>(</span><span class=n>T</span><span class=p>)</span><span class=w> </span><span class=o><=</span><span class=w> </span><span class=mi>32</span><span class=o>>::</span><span class=n>type</span><span class=o>></span>
|
||||
<span class=k>struct</span><span class=w> </span><span class=nc>less_than_32_serializer</span><span class=w> </span><span class=p>{</span>
|
||||
@@ -357,4 +357,4 @@
|
||||
<span class=w> </span><span class=n>value</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>j</span><span class=p>.</span><span class=k>template</span><span class=w> </span><span class=n>get</span><span class=o><</span><span class=n>T</span><span class=o>></span><span class=p>();</span><span class=w> </span><span class=c1>// oops!</span>
|
||||
<span class=w> </span><span class=p>}</span>
|
||||
<span class=p>};</span>
|
||||
</code></pre></div> <h2 id=see-also>See also<a class=headerlink href=#see-also title="Permanent link">¶</a></h2> <ul> <li><a href=../type_recipes/ >Recipes for common types</a> - smart pointers, class hierarchies, <code>std::variant</code>, and <code>std::chrono</code></li> <li><a href=../conversions/ >Converting values</a> - the general overview of <code>get</code>/<code>get_to</code> and implicit conversions</li> <li><a href=../enum_conversion/ >Specializing enum conversion</a> - map enums to <abbr title="JavaScript Object Notation">JSON</abbr> strings instead of integers</li> <li><a href=../macros/ >Supported macros</a> - reference for <code>NLOHMANN_DEFINE_TYPE_*</code> and related macros</li> <li><a href=../../api/adl_serializer/ ><code>adl_serializer</code></a> - the default <code>JSONSerializer</code> used in the conversion dispatch</li> </ul> <!-- https://squidfunk.github.io/mkdocs-material/reference/tooltips/#adding-a-glossary --> <aside class=md-source-file> <span class=md-source-file__fact> <span class=md-icon title="Last update"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M21 13.1c-.1 0-.3.1-.4.2l-1 1 2.1 2.1 1-1c.2-.2.2-.6 0-.8l-1.3-1.3c-.1-.1-.2-.2-.4-.2m-1.9 1.8-6.1 6V23h2.1l6.1-6.1zM12.5 7v5.2l4 2.4-1 1L11 13V7zM11 21.9c-5.1-.5-9-4.8-9-9.9C2 6.5 6.5 2 12 2c5.3 0 9.6 4.1 10 9.3-.3-.1-.6-.2-1-.2s-.7.1-1 .2C19.6 7.2 16.2 4 12 4c-4.4 0-8 3.6-8 8 0 4.1 3.1 7.5 7.1 7.9l-.1.2z"/></svg> </span> <span class="git-revision-date-localized-plugin git-revision-date-localized-plugin-date" title="October 25, 2026 11:07:51 UTC">October 25, 2026</span> </span> </aside> </article> </div> <script>var tabs=__md_get("__tabs");if(Array.isArray(tabs))e:for(var set of document.querySelectorAll(".tabbed-set")){var labels=set.querySelector(".tabbed-labels");for(var tab of tabs)for(var label of labels.getElementsByTagName("label"))if(label.innerText.trim()===tab){var input=document.getElementById(label.htmlFor);input.checked=!0;continue e}}</script> <script>var target=document.getElementById(location.hash.slice(1));target&&target.name&&(target.checked=target.name.startsWith("__tabbed_"))</script> </div> <button type=button class="md-top md-icon" data-md-component=top hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M13 20h-2V8l-5.5 5.5-1.42-1.42L12 4.16l7.92 7.92-1.42 1.42L13 8z"/></svg> Back to top </button> </main> <footer class=md-footer> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class=md-copyright> <div class=md-copyright__highlight> Copyright © 2013-2026 Niels Lohmann </div> </div> <div class=md-social> <a href="https://github.com/nlohmann" target="_blank" rel="noopener" title="github.com" class="md-social__link"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 512 512"><!-- Font Awesome Free 7.1.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2025 Fonticons, Inc.--><path d="M173.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6m-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3m44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9M252.8 8C114.1 8 8 113.3 8 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C436.2 457.8 504 362.9 504 252 504 113.3 391.5 8 252.8 8M105.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1m-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7m32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1m-11.4-14.7c-1.6 1-1.6 3.6 0 5.9s4.3 3.3 5.6 2.3c1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2"/></svg> </a> <a href="https://www.linkedin.com/in/nielslohmann/" target="_blank" rel="noopener" title="www.linkedin.com" class="md-social__link"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 448 512"><!-- Font Awesome Free 7.1.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2025 Fonticons, Inc.--><path d="M416 32H31.9C14.3 32 0 46.5 0 64.3v383.4C0 465.5 14.3 480 31.9 480H416c17.6 0 32-14.5 32-32.3V64.3c0-17.8-14.4-32.3-32-32.3M135.4 416H69V202.2h66.5V416zM102.2 96a38.5 38.5 0 1 1 0 77 38.5 38.5 0 1 1 0-77m282.1 320h-66.4V312c0-24.8-.5-56.7-34.5-Line truncated
|
||||
</code></pre></div> <h2 id=see-also>See also<a class=headerlink href=#see-also title="Permanent link">¶</a></h2> <ul> <li><a href=../type_recipes/ >Recipes for common types</a> - smart pointers, class hierarchies, <code>std::variant</code>, and <code>std::chrono</code></li> <li><a href=../conversions/ >Converting values</a> - the general overview of <code>get</code>/<code>get_to</code> and implicit conversions</li> <li><a href=../enum_conversion/ >Specializing enum conversion</a> - map enums to <abbr title="JavaScript Object Notation">JSON</abbr> strings instead of integers</li> <li><a href=../macros/ >Supported macros</a> - reference for <code>NLOHMANN_DEFINE_TYPE_*</code> and related macros</li> <li><a href=../../api/adl_serializer/ ><code>adl_serializer</code></a> - the default <code>JSONSerializer</code> used in the conversion dispatch</li> <li><a href=../../api/macros/nlohmann_define_type_intrusive/ ><code>NLOHMANN_DEFINE_TYPE_INTRUSIVE</code></a> - generate the conversion functions inside the type</li> <li><a href=../../api/macros/nlohmann_define_type_non_intrusive/ ><code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE</code></a> - generate the conversion functions outside the type</li> <li><a href=../../api/macros/nlohmann_define_type_with_names/ ><code>NLOHMANN_DEFINE_TYPE_WITH_NAMES</code></a> - use <abbr title="JavaScript Object Notation">JSON</abbr> keys that differ from the member names</li> <li><a href=../../api/macros/nlohmann_define_derived_type/ ><code>NLOHMANN_DEFINE_DERIVED_TYPE</code></a> - generate the conversion functions for derived classes</li> <li><a href=../../api/macros/nlohmann_json_serialize_enum/ ><code>NLOHMANN_JSON_SERIALIZE_ENUM</code></a> - map enum values to <abbr title="JavaScript Object Notation">JSON</abbr> values</li> <li><a href=../../api/basic_json/get/ ><code>get</code></a> - convert a <abbr title="JavaScript Object Notation">JSON</abbr> value to a C++ type</li> <li><a href=../../api/basic_json/get_to/ ><code>get_to</code></a> - convert a <abbr title="JavaScript Object Notation">JSON</abbr> value into an existing variable</li> <li><a href=../../api/basic_json/json_serializer/ ><code>json_serializer</code></a> - the <code>JSONSerializer</code> template parameter</li> </ul> <!-- https://squidfunk.github.io/mkdocs-material/reference/tooltips/#adding-a-glossary --> <aside class=md-source-file> <span class=md-source-file__fact> <span class=md-icon title="Last update"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M21 13.1c-.1 0-.3.1-.4.2l-1 1 2.1 2.1 1-1c.2-.2.2-.6 0-.8l-1.3-1.3c-.1-.1-.2-.2-.4-.2m-1.9 1.8-6.1 6V23h2.1l6.1-6.1zM12.5 7v5.2l4 2.4-1 1L11 13V7zM11 21.9c-5.1-.5-9-4.8-9-9.9C2 6.5 6.5 2 12 2c5.3 0 9.6 4.1 10 9.3-.3-.1-.6-.2-1-.2s-.7.1-1 .2C19.6 7.2 16.2 4 12 4c-4.4 0-8 3.6-8 8 0 4.1 3.1 7.5 7.1 7.9l-.1.2z"/></svg> </span> <span class="git-revision-date-localized-plugin git-revision-date-localized-plugin-date" title="October 27, 2026 06:41:42 UTC">October 27, 2026</span> </span> </aside> </article> </div> <script>var tabs=__md_get("__tabs");if(Array.isArray(tabs))e:for(var set of document.querySelectorAll(".tabbed-set")){var labels=set.querySelector(".tabbed-labels");for(var tab of tabs)for(var label of labels.getElementsByTagName("label"))if(label.innerText.trim()===tab){var input=document.getElementById(label.htmlFor);input.checked=!0;continue e}}</script> <script>var target=document.getElementById(location.hash.slice(1));target&&target.name&&(target.checked=target.name.startsWith("__tabbed_"))</script> </div> <button type=button class="md-top md-icon" data-md-component=top hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M13 20h-2V8l-5.5 5.5-1.42-1.42L12 4.16l7.92 7.92-1.42 1.42L13 8z"/></svg> Back to top </button> </main> <footer class=md-footer> <nav class="md-footer__inner md-grid" aria-label=Footer> <a href=../ class="md-footer__link md-footer__link--prev" aria-label="Previous: Features"> <div class="md-footer__button md-icon"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11z"/></svg> </div> <div class=md-footer__title> <span class=md-footer__direction> Previous </span> <div class=md-ellipsis> Features </div> </div> </a> <a href=../type_recipes/ class="md-footer__link md-footer__link--next" aria-label="Next: Recipes for Common Types"> <div class=md-footer__title> <span class=md-footer__direction> Next </span> <div class=md-ellipsis> Recipes for Common Types </div> </div> <div class="md-footer__button md-icon"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M4 11v2h12l-5.5 5.5 1.42 1.42L19.84 12l-7.92-7.92L10.5 5.5 16 11z"/></svg> </div> </a> </nav> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class=md-copyright> <div class=md-copyright__highlight> Copyright © 2013-2026 Niels Lohmann </div> </div> <div class=md-social> <a href="https://github.com/nlohmann" target="_blankLine truncated
|
||||
@@ -190,26 +190,28 @@ For all the macros, the first parameter is the name of the class/struct. The `DE
|
||||
|
||||
```
|
||||
flowchart TD
|
||||
A["choosing a NLOHMANN_DEFINE_* macro"] --> B{"adding fields to a base class?"}
|
||||
A["choosing a NLOHMANN_DEFINE_* macro"] --> B{{"adding fields to a base class?"}}
|
||||
B -->|"yes"| C["...DERIVED_TYPE..."]
|
||||
B -->|"no"| D["...TYPE..."]
|
||||
C --> E{"need access to private members?"}
|
||||
C --> E{{"need access to private members?"}}
|
||||
D --> E
|
||||
E -->|"yes"| F["...INTRUSIVE... (used inside the class)"]
|
||||
E -->|"no"| G["...NON_INTRUSIVE... (used in the namespace)"]
|
||||
F --> H{"only serializing, never parsing back?"}
|
||||
F --> H{{"only serializing, never parsing back?"}}
|
||||
G --> H
|
||||
H -->|"yes"| I["...ONLY_SERIALIZE"]
|
||||
H -->|"no"| J{"allow missing keys when parsing?"}
|
||||
H -->|"no"| J{{"allow missing keys when parsing?"}}
|
||||
J -->|"yes"| K["...WITH_DEFAULT"]
|
||||
J -->|"no"| L["plain (missing keys throw)"]
|
||||
I --> M{"need custom JSON key names?"}
|
||||
I --> M{{"need custom JSON key names?"}}
|
||||
K --> M
|
||||
L --> M
|
||||
M -->|"yes"| N["...WITH_NAMES"]
|
||||
M -->|"no"| O["done"]
|
||||
```
|
||||
|
||||
Decision tree for choosing a `NLOHMANN_DEFINE_*` macro: answer the questions from top to bottom; each answer picks one part of the macro name, and the parts are combined in this order. The table below lists the resulting macros.
|
||||
|
||||
| Need access to private members | Need only serialization | Allow missing values when de-serializing | macro |
|
||||
| ------------------------------ | ----------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| | | | [**NLOHMANN_DEFINE_TYPE_INTRUSIVE**](https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/index.md) |
|
||||
@@ -219,6 +221,8 @@ flowchart TD
|
||||
| | | | [**NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT**](https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/index.md) |
|
||||
| | | | [**NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE**](https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/index.md) |
|
||||
|
||||
Macros for classes and structs without a base class. A green check means yes, a red cross means no, and a grey skip sign means the column does not apply, as a macro that only serializes never reads values.
|
||||
|
||||
For *derived* classes and structs, use the following macros
|
||||
|
||||
| Need access to private members | Need only serialization | Allow missing values when de-serializing | macro |
|
||||
@@ -230,11 +234,26 @@ For *derived* classes and structs, use the following macros
|
||||
| | | | [**NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT**](https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/index.md) |
|
||||
| | | | [**NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE**](https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/index.md) |
|
||||
|
||||
Macros for derived classes and structs, read as Table 1.
|
||||
|
||||
Implementation limits
|
||||
|
||||
- The current macro implementations are limited to at most 63 member variables. If you want to serialize/deserialize types with more than 63 member variables, you need to define the `to_json`/`from_json` functions manually.
|
||||
- For the `WITH_NAMES` variants the limit is halved to 31 member variables.
|
||||
|
||||
To pick the macro for your own type and get code to start from, answer the questions below.
|
||||
|
||||
- Members are private: use an `INTRUSIVE` macro inside the class ([reference](https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/index.md)).
|
||||
- All members are public, or you cannot edit the class: use a `NON_INTRUSIVE` macro in the class's namespace ([reference](https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/index.md)).
|
||||
- The class adds members to a serializable base class: use a `DERIVED_TYPE` macro with the base class as second argument ([reference](https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/index.md)).
|
||||
- Missing keys should keep their default values: append `_WITH_DEFAULT`; otherwise a missing key throws.
|
||||
- You only convert to JSON: append `_ONLY_SERIALIZE` instead.
|
||||
- JSON keys differ from the member names: append `_WITH_NAMES` and write `"key", member` pairs ([reference](https://json.nlohmann.me/api/macros/nlohmann_define_type_with_names/index.md)).
|
||||
- Private members of a class you cannot edit: no macro works; write the conversion by hand ([third-party types](#how-do-i-convert-third-party-types)).
|
||||
- The type is not default constructible and is converted in both directions: no macro works; specialize `adl_serializer` with a `from_json` that returns the value, or append `_ONLY_SERIALIZE` if you only convert to JSON ([non-default-constructible types](#how-can-i-use-get-for-non-default-constructiblenon-copyable-types)).
|
||||
|
||||
Macro chooser: each answer selects one part of the macro name; the generated program defines the type, calls the macro and converts a value to JSON and back. Combinations that no macro supports show the alternative instead of code.
|
||||
|
||||
Example: using the `NLOHMANN_DEFINE_TYPE_*` macros
|
||||
|
||||
The `to_json`/`from_json` functions for the `person` struct above can be created with:
|
||||
@@ -301,7 +320,7 @@ Members declared as raw C-style arrays (e.g., `char buf[1024]`) do not round-tri
|
||||
|
||||
Macros and `nlohmann::ordered_json`
|
||||
|
||||
The `NLOHMANN_DEFINE_TYPE_*`/`NLOHMANN_DEFINE_DERIVED_TYPE_*` macros are generic over any `basic_json` specialization, including `nlohmann::ordered_json`. Simply use `ordered_json` as the target type and members are serialized in declaration order -- no separate macro or extra code is needed.
|
||||
The `NLOHMANN_DEFINE_TYPE_*`/`NLOHMANN_DEFINE_DERIVED_TYPE_*` macros are generic over any `basic_json` specialization, including `nlohmann::ordered_json`. Simply use `ordered_json` as the target type and members are serialized in declaration order — no separate macro or extra code is needed.
|
||||
|
||||
```
|
||||
namespace ns {
|
||||
@@ -330,7 +349,7 @@ nlohmann::json j = m; // {}
|
||||
|
||||
No macro for non-default-constructible types
|
||||
|
||||
There is currently no `NLOHMANN_DEFINE_TYPE_*`-style macro for types that are not [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). This is not an intentional omission of documentation -- no such macro exists yet; see [How can I use `get()` for non-default constructible/non-copyable types?](#how-can-i-use-get-for-non-default-constructiblenon-copyable-types) for the manual pattern to use instead.
|
||||
There is currently no `NLOHMANN_DEFINE_TYPE_*`-style macro for types that are not [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). This is not an intentional omission of documentation — no such macro exists yet; see [How can I use `get()` for non-default constructible/non-copyable types?](#how-can-i-use-get-for-non-default-constructiblenon-copyable-types) for the manual pattern to use instead.
|
||||
|
||||
## How do I convert third-party types?
|
||||
|
||||
@@ -344,6 +363,8 @@ flowchart LR
|
||||
B -->|"user specialization replaces the default"| E["user's adl_serializer specialization for T"]
|
||||
```
|
||||
|
||||
How a conversion between `json` and a type `T` is dispatched: the default `adl_serializer` calls the free `to_json`/`from_json` functions found by argument-dependent lookup, while a user specialization of `adl_serializer` replaces this path.
|
||||
|
||||
The library uses **JSON Serializers** to convert types to JSON. The default serializer for `nlohmann::json` is `nlohmann::adl_serializer` (ADL means [Argument-Dependent Lookup](https://en.cppreference.com/w/cpp/language/adl)).
|
||||
|
||||
It is implemented like this (simplified):
|
||||
@@ -512,7 +533,7 @@ For smart pointers, class hierarchies, `std::variant`, and `std::chrono`, see [R
|
||||
|
||||
## Why can't I convert to/from `std::any`?
|
||||
|
||||
`std::any` is intentionally excluded from `get<T>()`/generic conversion support, so `get<std::any>()` and containers like `std::map<std::string, std::any>` fail to compile by design -- there is no way to know, from a `json` value alone, which concrete type to store inside the `std::any`. To work with heterogeneous JSON values, dispatch on the value's type manually and construct the `std::any` (or extract from it) yourself:
|
||||
`std::any` is intentionally excluded from `get<T>()`/generic conversion support, so `get<std::any>()` and containers like `std::map<std::string, std::any>` fail to compile by design — there is no way to know, from a `json` value alone, which concrete type to store inside the `std::any`. To work with heterogeneous JSON values, dispatch on the value's type manually and construct the `std::any` (or extract from it) yourself:
|
||||
|
||||
```
|
||||
std::any value_to_any(const json& j) {
|
||||
@@ -539,7 +560,7 @@ A `std::map`/`std::unordered_map` whose key type is not string-like (e.g., `std:
|
||||
|
||||
## Why does `std::wstring` convert or dump incorrectly?
|
||||
|
||||
The library assumes UTF-8 encoding internally, so `std::wstring` is not supported out of the box -- see the FAQ entry on [wide string handling](https://json.nlohmann.me/home/faq/#wide-string-handling) for why, and for a UTF-8 conversion recipe.
|
||||
The library assumes UTF-8 encoding internally, so `std::wstring` is not supported out of the box — see the FAQ entry on [wide string handling](https://json.nlohmann.me/home/faq/#wide-string-handling) for why, and for a UTF-8 conversion recipe.
|
||||
|
||||
## Can I write my own serializer? (Advanced use)
|
||||
|
||||
@@ -604,3 +625,11 @@ struct bad_serializer
|
||||
- [Specializing enum conversion](https://json.nlohmann.me/features/enum_conversion/index.md) - map enums to JSON strings instead of integers
|
||||
- [Supported macros](https://json.nlohmann.me/features/macros/index.md) - reference for `NLOHMANN_DEFINE_TYPE_*` and related macros
|
||||
- [`adl_serializer`](https://json.nlohmann.me/api/adl_serializer/index.md) - the default `JSONSerializer` used in the conversion dispatch
|
||||
- [`NLOHMANN_DEFINE_TYPE_INTRUSIVE`](https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/index.md) - generate the conversion functions inside the type
|
||||
- [`NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE`](https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/index.md) - generate the conversion functions outside the type
|
||||
- [`NLOHMANN_DEFINE_TYPE_WITH_NAMES`](https://json.nlohmann.me/api/macros/nlohmann_define_type_with_names/index.md) - use JSON keys that differ from the member names
|
||||
- [`NLOHMANN_DEFINE_DERIVED_TYPE`](https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/index.md) - generate the conversion functions for derived classes
|
||||
- [`NLOHMANN_JSON_SERIALIZE_ENUM`](https://json.nlohmann.me/api/macros/nlohmann_json_serialize_enum/index.md) - map enum values to JSON values
|
||||
- [`get`](https://json.nlohmann.me/api/basic_json/get/index.md) - convert a JSON value to a C++ type
|
||||
- [`get_to`](https://json.nlohmann.me/api/basic_json/get_to/index.md) - convert a JSON value into an existing variable
|
||||
- [`json_serializer`](https://json.nlohmann.me/api/basic_json/json_serializer/index.md) - the `JSONSerializer` template parameter
|
||||
Reference in new issue
Block a user