deploy: 63c10a51fc
This commit is contained in:
1 parent
2aaa1d24ef
commit
a410b4f40f
741 files changed
+8115
-2252
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=../binary_formats/ 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 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=author content="Niels Lohmann"><link href="https://json.nlohmann.me/features/arbitrary_types/" rel="canonical"><link href=../ rel=prev><link href=../binary_formats/ 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 Line 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>
|
||||
@@ -50,7 +50,96 @@
|
||||
<span class=w> </span><span class=n>j</span><span class=p>.</span><span class=n>at</span><span class=p>(</span><span class=s>"age"</span><span class=p>).</span><span class=n>get_to</span><span class=p>(</span><span class=n>p</span><span class=p>.</span><span class=n>age</span><span class=p>);</span>
|
||||
<span class=w> </span><span class=p>}</span>
|
||||
<span class=p>}</span><span class=w> </span><span class=c1>// namespace ns</span>
|
||||
</code></pre></div> <p>That's all! When calling the <code>json</code> constructor with your type, your custom <code>to_json</code> method will be automatically called. Likewise, when calling <code>get<your_type>()</code> or <code>get_to(your_type&)</code>, the <code>from_json</code> method will be called.</p> <p>Some important things:</p> <ul> <li>Those methods <strong>MUST</strong> be in your type's namespace (which can be the global namespace), or the library will not be able to locate them (in this example, they are in namespace <code>ns</code>, where <code>person</code> is defined).</li> <li>Those methods <strong>MUST</strong> be available (e.g., proper headers must be included) everywhere you use these conversions. Look at <a href="https://github.com/nlohmann/json/issues/1108">#1108</a> for errors that may occur otherwise.</li> <li>When using <code>get<your_type>()</code>, <code>your_type</code> <strong>MUST</strong> be <a href="https://en.cppreference.com/w/cpp/named_req/DefaultConstructible">DefaultConstructible</a>. (There is a way to bypass this requirement described later.)</li> <li>In function <code>from_json</code>, use function <a href=../../api/basic_json/at/ ><code>at()</code></a> to access the object values rather than <code>operator[]</code>. In case a key does not exist, <code>at</code> throws an exception that you can handle, whereas <code>operator[]</code> exhibits undefined behavior.</li> <li>You do not need to add serializers or deserializers for <abbr title="Standard Template Library">STL</abbr> types like <code>std::vector</code>: the library already implements these.</li> </ul> <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> <table> <thead> <tr> <th>Need access to private members</th> <th>Need only de-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 Line truncated
|
||||
</code></pre></div> <p>That's all! When calling the <code>json</code> constructor with your type, your custom <code>to_json</code> method will be automatically called. Likewise, when calling <code>get<your_type>()</code> or <code>get_to(your_type&)</code>, the <code>from_json</code> method will be called.</p> <p>Some important things:</p> <ul> <li>Those methods <strong>MUST</strong> be in your type's namespace (which can be the global namespace), or the library will not be able to locate them (in this example, they are in namespace <code>ns</code>, where <code>person</code> is defined).</li> <li>Those methods <strong>MUST</strong> be available (e.g., proper headers must be included) everywhere you use these conversions. Look at <a href="https://github.com/nlohmann/json/issues/1108">#1108</a> for errors that may occur otherwise.</li> <li>When using <code>get<your_type>()</code>, <code>your_type</code> <strong>MUST</strong> be <a href="https://en.cppreference.com/w/cpp/named_req/DefaultConstructible">DefaultConstructible</a>. (There is a way to bypass this requirement described later.)</li> <li>In function <code>from_json</code>, use function <a href=../../api/basic_json/at/ ><code>at()</code></a> to access the object values rather than <code>operator[]</code>. In case a key does not exist, <code>at</code> throws an exception that you can handle, whereas <code>operator[]</code> exhibits undefined behavior.</li> <li>You do not need to add serializers or deserializers for <abbr title="Standard Template Library">STL</abbr> types like <code>std::vector</code>: the library already implements these.</li> </ul> <details class=example> <summary>Example: serialize a <code>person</code> to <abbr title="JavaScript Object Notation">JSON</abbr> with <code>to_json</code></summary> <div class=highlight><pre><span></span><code><span class=cp>#include</span><span class=w> </span><span class=cpf><iostream></span>
|
||||
<span class=cp>#include</span><span class=w> </span><span class=cpf><nlohmann/json.hpp></span>
|
||||
|
||||
<span class=k>using</span><span class=w> </span><span class=n>json</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>nlohmann</span><span class=o>::</span><span class=n>json</span><span class=p>;</span>
|
||||
|
||||
<span class=k>namespace</span><span class=w> </span><span class=nn>ns</span>
|
||||
<span class=p>{</span>
|
||||
<span class=c1>// a simple struct to model a person</span>
|
||||
<span class=k>struct</span><span class=w> </span><span class=nc>person</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>
|
||||
<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>address</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=kt>int</span><span class=w> </span><span class=n>age</span><span class=p>;</span>
|
||||
<span class=p>};</span>
|
||||
<span class=p>}</span><span class=w> </span><span class=c1>// namespace ns</span>
|
||||
|
||||
<span class=k>namespace</span><span class=w> </span><span class=nn>ns</span>
|
||||
<span class=p>{</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>person</span><span class=o>&</span><span class=w> </span><span class=n>p</span><span class=p>)</span>
|
||||
<span class=p>{</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>json</span><span class=p>{</span><span class=w> </span><span class=p>{</span><span class=s>"name"</span><span class=p>,</span><span class=w> </span><span class=n>p</span><span class=p>.</span><span class=n>name</span><span class=p>},</span><span class=w> </span><span class=p>{</span><span class=s>"address"</span><span class=p>,</span><span class=w> </span><span class=n>p</span><span class=p>.</span><span class=n>address</span><span class=p>},</span><span class=w> </span><span class=p>{</span><span class=s>"age"</span><span class=p>,</span><span class=w> </span><span class=n>p</span><span class=p>.</span><span class=n>age</span><span class=p>}</span><span class=w> </span><span class=p>};</span>
|
||||
<span class=p>}</span>
|
||||
<span class=p>}</span><span class=w> </span><span class=c1>// namespace ns</span>
|
||||
|
||||
<span class=kt>int</span><span class=w> </span><span class=n>main</span><span class=p>()</span>
|
||||
<span class=p>{</span>
|
||||
<span class=w> </span><span class=n>ns</span><span class=o>::</span><span class=n>person</span><span class=w> </span><span class=n>p</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=p>{</span><span class=s>"Ned Flanders"</span><span class=p>,</span><span class=w> </span><span class=s>"744 Evergreen Terrace"</span><span class=p>,</span><span class=w> </span><span class=mi>60</span><span class=p>};</span>
|
||||
|
||||
<span class=w> </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>p</span><span class=p>;</span>
|
||||
|
||||
<span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>cout</span><span class=w> </span><span class=o><<</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>endl</span><span class=p>;</span>
|
||||
<span class=p>}</span>
|
||||
</code></pre></div> <p>Output:</p> <div class=highlight><pre><span></span><code><span class=p>{</span><span class=nt>"address"</span><span class=p>:</span><span class=s2>"744 Evergreen Terrace"</span><span class=p>,</span><span class=nt>"age"</span><span class=p>:</span><span class=mi>60</span><span class=p>,</span><span class=nt>"name"</span><span class=p>:</span><span class=s2>"Ned Flanders"</span><span class=p>}</span>
|
||||
</code></pre></div> </details> <details class=example> <summary>Example: deserialize a <code>person</code> from <abbr title="JavaScript Object Notation">JSON</abbr> with <code>from_json</code></summary> <div class=highlight><pre><span></span><code><span class=cp>#include</span><span class=w> </span><span class=cpf><iostream></span>
|
||||
<span class=cp>#include</span><span class=w> </span><span class=cpf><nlohmann/json.hpp></span>
|
||||
|
||||
<span class=k>using</span><span class=w> </span><span class=n>json</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>nlohmann</span><span class=o>::</span><span class=n>json</span><span class=p>;</span>
|
||||
|
||||
<span class=k>namespace</span><span class=w> </span><span class=nn>ns</span>
|
||||
<span class=p>{</span>
|
||||
<span class=c1>// a simple struct to model a person</span>
|
||||
<span class=k>struct</span><span class=w> </span><span class=nc>person</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>
|
||||
<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>address</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=kt>int</span><span class=w> </span><span class=n>age</span><span class=p>;</span>
|
||||
<span class=p>};</span>
|
||||
<span class=p>}</span><span class=w> </span><span class=c1>// namespace ns</span>
|
||||
|
||||
<span class=k>namespace</span><span class=w> </span><span class=nn>ns</span>
|
||||
<span class=p>{</span>
|
||||
<span class=kt>void</span><span class=w> </span><span class=nf>from_json</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=n>person</span><span class=o>&</span><span class=w> </span><span class=n>p</span><span class=p>)</span>
|
||||
<span class=p>{</span>
|
||||
<span class=w> </span><span class=n>j</span><span class=p>.</span><span class=n>at</span><span class=p>(</span><span class=s>"name"</span><span class=p>).</span><span class=n>get_to</span><span class=p>(</span><span class=n>p</span><span class=p>.</span><span class=n>name</span><span class=p>);</span>
|
||||
<span class=w> </span><span class=n>j</span><span class=p>.</span><span class=n>at</span><span class=p>(</span><span class=s>"address"</span><span class=p>).</span><span class=n>get_to</span><span class=p>(</span><span class=n>p</span><span class=p>.</span><span class=n>address</span><span class=p>);</span>
|
||||
<span class=w> </span><span class=n>j</span><span class=p>.</span><span class=n>at</span><span class=p>(</span><span class=s>"age"</span><span class=p>).</span><span class=n>get_to</span><span class=p>(</span><span class=n>p</span><span class=p>.</span><span class=n>age</span><span class=p>);</span>
|
||||
<span class=p>}</span>
|
||||
<span class=p>}</span><span class=w> </span><span class=c1>// namespace ns</span>
|
||||
|
||||
<span class=kt>int</span><span class=w> </span><span class=n>main</span><span class=p>()</span>
|
||||
<span class=p>{</span>
|
||||
<span class=w> </span><span class=n>json</span><span class=w> </span><span class=n>j</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=n>j</span><span class=p>[</span><span class=s>"name"</span><span class=p>]</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=s>"Ned Flanders"</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=n>j</span><span class=p>[</span><span class=s>"address"</span><span class=p>]</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=s>"744 Evergreen Terrace"</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=n>j</span><span class=p>[</span><span class=s>"age"</span><span class=p>]</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=mi>60</span><span class=p>;</span>
|
||||
|
||||
<span class=w> </span><span class=k>auto</span><span class=w> </span><span class=n>p</span><span class=w> </span><span class=o>=</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=n>ns</span><span class=o>::</span><span class=n>person</span><span class=o>></span><span class=p>();</span>
|
||||
|
||||
<span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>cout</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=n>p</span><span class=p>.</span><span class=n>name</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=s>" ("</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=n>p</span><span class=p>.</span><span class=n>age</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=s>") lives in "</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=n>p</span><span class=p>.</span><span class=n>address</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>endl</span><span class=p>;</span>
|
||||
<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?"}
|
||||
B -->|"yes"| C["...DERIVED_TYPE..."]
|
||||
B -->|"no"| D["...TYPE..."]
|
||||
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?"}
|
||||
G --> H
|
||||
H -->|"yes"| I["...ONLY_SERIALIZE"]
|
||||
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?"}
|
||||
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
|
||||
<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>
|
||||
@@ -99,7 +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> <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>
|
||||
</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>
|
||||
<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>
|
||||
@@ -132,7 +225,61 @@
|
||||
<span class=w> </span><span class=p>}</span>
|
||||
<span class=p>};</span>
|
||||
<span class=n>NLOHMANN_JSON_NAMESPACE_END</span>
|
||||
</code></pre></div> <div class="admonition note"> <p class=admonition-title>ABI compatibility</p> <p>Use <a href=../../api/macros/nlohmann_json_namespace_begin/ ><code>NLOHMANN_JSON_NAMESPACE_BEGIN</code></a> and <code>NLOHMANN_JSON_NAMESPACE_END</code> instead of <code class=highlight><span class=k>namespace</span><span class=w> </span><span class=nn>nlohmann</span><span class=w> </span><span class=p>{</span><span class=w> </span><span class=p>}</span></code> in code which may be linked with different versions of this library.</p> </div> <h2 id=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 class=headerlink href=#how-can-i-use-get-for-non-default-constructiblenon-copyable-types title="Permanent link">¶</a></h2> <p>There is a way if your type is <a href="https://en.cppreference.com/w/cpp/named_req/MoveConstructible">MoveConstructible</a>. You will need to specialize the <code>adl_serializer</code> as well, but with a special <code>from_json</code> overload:</p> <div class=highlight><pre><span></span><code><span class=k>struct</span><span class=w> </span><span class=nc>move_only_type</span><span class=w> </span><span class=p>{</span>
|
||||
</code></pre></div> <div class="admonition note"> <p class=admonition-title>ABI compatibility</p> <p>Use <a href=../../api/macros/nlohmann_json_namespace_begin/ ><code>NLOHMANN_JSON_NAMESPACE_BEGIN</code></a> and <code>NLOHMANN_JSON_NAMESPACE_END</code> instead of <code class=highlight><span class=k>namespace</span><span class=w> </span><span class=nn>nlohmann</span><span class=w> </span><span class=p>{</span><span class=w> </span><span class=p>}</span></code> in code which may be linked with different versions of this library.</p> </div> <h2 id=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 class=headerlink href=#how-can-i-use-get-for-non-default-constructiblenon-copyable-types title="Permanent link">¶</a></h2> <p>For a type that is not <a href="https://en.cppreference.com/w/cpp/named_req/DefaultConstructible">DefaultConstructible</a> but is otherwise an ordinary value type, specialize <code>adl_serializer</code> with a <code>from_json</code> overload that returns the value instead of writing into a reference:</p> <details class=example> <summary>Example: <code>get()</code> for a non-default-constructible type</summary> <div class=highlight><pre><span></span><code><span class=cp>#include</span><span class=w> </span><span class=cpf><iostream></span>
|
||||
<span class=cp>#include</span><span class=w> </span><span class=cpf><nlohmann/json.hpp></span>
|
||||
|
||||
<span class=k>using</span><span class=w> </span><span class=n>json</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>nlohmann</span><span class=o>::</span><span class=n>json</span><span class=p>;</span>
|
||||
|
||||
<span class=k>namespace</span><span class=w> </span><span class=nn>ns</span>
|
||||
<span class=p>{</span>
|
||||
<span class=c1>// a simple struct to model a person (not default constructible)</span>
|
||||
<span class=k>struct</span><span class=w> </span><span class=nc>person</span>
|
||||
<span class=p>{</span>
|
||||
<span class=w> </span><span class=n>person</span><span class=p>(</span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=w> </span><span class=n>n</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>a</span><span class=p>,</span><span class=w> </span><span class=kt>int</span><span class=w> </span><span class=n>aa</span><span class=p>)</span>
|
||||
<span class=w> </span><span class=o>:</span><span class=w> </span><span class=n>name</span><span class=p>(</span><span class=n>std</span><span class=o>::</span><span class=n>move</span><span class=p>(</span><span class=n>n</span><span class=p>)),</span><span class=w> </span><span class=n>address</span><span class=p>(</span><span class=n>std</span><span class=o>::</span><span class=n>move</span><span class=p>(</span><span class=n>a</span><span class=p>)),</span><span class=w> </span><span class=n>age</span><span class=p>(</span><span class=n>aa</span><span class=p>)</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>
|
||||
<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>address</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=kt>int</span><span class=w> </span><span class=n>age</span><span class=p>;</span>
|
||||
<span class=p>};</span>
|
||||
<span class=p>}</span><span class=w> </span><span class=c1>// namespace ns</span>
|
||||
|
||||
<span class=k>namespace</span><span class=w> </span><span class=nn>nlohmann</span>
|
||||
<span class=p>{</span>
|
||||
<span class=k>template</span><span class=w> </span><span class=o><></span>
|
||||
<span class=k>struct</span><span class=w> </span><span class=nc>adl_serializer</span><span class=o><</span><span class=n>ns</span><span class=o>::</span><span class=n>person</span><span class=o>></span>
|
||||
<span class=p>{</span>
|
||||
<span class=w> </span><span class=k>static</span><span class=w> </span><span class=n>ns</span><span class=o>::</span><span class=n>person</span><span class=w> </span><span class=nf>from_json</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>{</span>
|
||||
<span class=w> </span><span class=k>return</span><span class=w> </span><span class=p>{</span><span class=n>j</span><span class=p>.</span><span class=n>at</span><span class=p>(</span><span class=s>"name"</span><span class=p>),</span><span class=w> </span><span class=n>j</span><span class=p>.</span><span class=n>at</span><span class=p>(</span><span class=s>"address"</span><span class=p>),</span><span class=w> </span><span class=n>j</span><span class=p>.</span><span class=n>at</span><span class=p>(</span><span class=s>"age"</span><span class=p>)};</span>
|
||||
<span class=w> </span><span class=p>}</span>
|
||||
|
||||
<span class=w> </span><span class=c1>// Here's the catch! You must provide a to_json method! Otherwise, you</span>
|
||||
<span class=w> </span><span class=c1>// will not be able to convert person to json, since you fully</span>
|
||||
<span class=w> </span><span class=c1>// specialized adl_serializer on that type</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=n>ns</span><span class=o>::</span><span class=n>person</span><span class=w> </span><span class=n>p</span><span class=p>)</span>
|
||||
<span class=w> </span><span class=p>{</span>
|
||||
<span class=w> </span><span class=n>j</span><span class=p>[</span><span class=s>"name"</span><span class=p>]</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>p</span><span class=p>.</span><span class=n>name</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=n>j</span><span class=p>[</span><span class=s>"address"</span><span class=p>]</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>p</span><span class=p>.</span><span class=n>address</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=n>j</span><span class=p>[</span><span class=s>"age"</span><span class=p>]</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>p</span><span class=p>.</span><span class=n>age</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=p>}</span>
|
||||
<span class=p>};</span>
|
||||
<span class=p>}</span><span class=w> </span><span class=c1>// namespace nlohmann</span>
|
||||
|
||||
<span class=kt>int</span><span class=w> </span><span class=n>main</span><span class=p>()</span>
|
||||
<span class=p>{</span>
|
||||
<span class=w> </span><span class=n>json</span><span class=w> </span><span class=n>j</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=n>j</span><span class=p>[</span><span class=s>"name"</span><span class=p>]</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=s>"Ned Flanders"</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=n>j</span><span class=p>[</span><span class=s>"address"</span><span class=p>]</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=s>"744 Evergreen Terrace"</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=n>j</span><span class=p>[</span><span class=s>"age"</span><span class=p>]</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=mi>60</span><span class=p>;</span>
|
||||
|
||||
<span class=w> </span><span class=k>auto</span><span class=w> </span><span class=n>p</span><span class=w> </span><span class=o>=</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=n>ns</span><span class=o>::</span><span class=n>person</span><span class=o>></span><span class=p>();</span>
|
||||
|
||||
<span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>cout</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=n>p</span><span class=p>.</span><span class=n>name</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=s>" ("</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=n>p</span><span class=p>.</span><span class=n>age</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=s>") lives in "</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=n>p</span><span class=p>.</span><span class=n>address</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>endl</span><span class=p>;</span>
|
||||
<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> <p>The same technique also works if your type is not copyable, as long as it is <a href="https://en.cppreference.com/w/cpp/named_req/MoveConstructible">MoveConstructible</a>:</p> <div class=highlight><pre><span></span><code><span class=k>struct</span><span class=w> </span><span class=nc>move_only_type</span><span class=w> </span><span class=p>{</span>
|
||||
<span class=w> </span><span class=n>move_only_type</span><span class=p>()</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=k>delete</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=n>move_only_type</span><span class=p>(</span><span class=kt>int</span><span class=w> </span><span class=n>ii</span><span class=p>)</span><span class=o>:</span><span class=w> </span><span class=n>i</span><span class=p>(</span><span class=n>ii</span><span class=p>)</span><span class=w> </span><span class=p>{}</span>
|
||||
<span class=w> </span><span class=n>move_only_type</span><span class=p>(</span><span class=k>const</span><span class=w> </span><span class=n>move_only_type</span><span class=o>&</span><span class=p>)</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=k>delete</span><span class=p>;</span>
|
||||
@@ -174,10 +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>) is serialized as a <abbr title="JavaScript Object Notation">JSON</abbr> <em>array</em> of 2-element <code>[key, value]</code> arrays, not as a <abbr title="JavaScript Object Notation">JSON</abbr> object -- <abbr title="JavaScript Object Notation">JSON</abbr> object keys must be strings, so the library cannot represent an integer-keyed map as an object.</p> <div class=highlight><pre><span></span><code><span class=n>std</span><span class=o>::</span><span class=n>map</span><span class=o><</span><span class=kt>int</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=o>></span><span class=w> </span><span class=n>m</span><span class=p>{{</span><span class=mi>1</span><span class=p>,</span><span class=w> </span><span class=s>"one"</span><span class=p>},</span><span class=w> </span><span class=p>{</span><span class=mi>2</span><span class=p>,</span><span class=w> </span><span class=s>"two"</span><span class=p>}};</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=c1>// j is [[1,"one"],[2,"two"]], not {"1":"one","2":"two"}</span>
|
||||
</code></pre></div> <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>
|
||||
@@ -196,7 +340,7 @@
|
||||
<span class=w> </span><span class=n>from_json</span><span class=p>(</span><span class=n>j</span><span class=p>,</span><span class=w> </span><span class=n>value</span><span class=p>);</span>
|
||||
<span class=w> </span><span class=p>}</span>
|
||||
<span class=p>};</span>
|
||||
</code></pre></div> <p>Be <strong>very</strong> careful when reimplementing your serializer, you can stack overflow if you don't pay attention:</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=p>,</span><span class=w> </span><span class=kt>void</span><span class=o>></span>
|
||||
</code></pre></div> <p>Be <strong>very</strong> careful when reimplementing your serializer, you can stack overflow if you don't pay attention:</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=p>,</span><span class=w> </span><span class=k>typename</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=kt>void</span><span class=o>></span>
|
||||
<span class=k>struct</span><span class=w> </span><span class=nc>bad_serializer</span>
|
||||
<span class=p>{</span>
|
||||
<span class=w> </span><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>BasicJsonType</span><span class=o>></span>
|
||||
@@ -213,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> <!-- 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 2, 2026 09:23:55 UTC">October 2, 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-56.7-34.6 0-39.9 27-39.9 54.9V416h-66.4V202.2h63.7v29.2h.9c8.9-16.8 30.6-34.5 62.9-34.5 67.2 0 79.7 44.3 79.7 101.9z"/></svg> </a> <a href="https://www.xing.com/profile/Niels_Lohmann" target="_blank" rel="noopener" title="www.xing.com" class="md-social__link"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 384 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="M162.7 210c-1.8 3.3-25.2 44.4-70.1 123.5-4.9 8.3-10.8 12.5-17.7 12.5H9.8c-7.7 0-12.1-7.5-8.5-14.4l69-121.3q.3 0 0-.3l-43.9-75.6c-4.3-7.8.3-14.1 8.5-14.1H100c7.3 0 13.3 4.1 18 12.2zM382.6 46.1l-144 253v.3L330.2 466c3.9 7.1.2 14.1-8.5 14.1h-65.2c-7.6 0-13.6-4-18-12.2l-92.4-168.5c3.3-5.8 51.5-90.8 144.8-255.2 4.6Line 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=../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 2, 2026 09:32:15 UTC">October 2, 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-56.7-34.6 0-39.9 27-39.9 54.9V416h-66.4V202.2h63.7v29.2h.9c8.9-16.8 30.6-34.5 62.9-34.5 67.2 0 79.7 44.3 79.7 101.9z"/></svg> </a> <a href="https://www.xing.coLine truncated
|
||||
@@ -79,6 +79,97 @@ Some important things:
|
||||
- In function `from_json`, use function [`at()`](https://json.nlohmann.me/api/basic_json/at/index.md) to access the object values rather than `operator[]`. In case a key does not exist, `at` throws an exception that you can handle, whereas `operator[]` exhibits undefined behavior.
|
||||
- You do not need to add serializers or deserializers for STL types like `std::vector`: the library already implements these.
|
||||
|
||||
Example: serialize a `person` to JSON with `to_json`
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
namespace ns
|
||||
{
|
||||
// a simple struct to model a person
|
||||
struct person
|
||||
{
|
||||
std::string name;
|
||||
std::string address;
|
||||
int age;
|
||||
};
|
||||
} // namespace ns
|
||||
|
||||
namespace ns
|
||||
{
|
||||
void to_json(json& j, const person& p)
|
||||
{
|
||||
j = json{ {"name", p.name}, {"address", p.address}, {"age", p.age} };
|
||||
}
|
||||
} // namespace ns
|
||||
|
||||
int main()
|
||||
{
|
||||
ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
|
||||
|
||||
json j = p;
|
||||
|
||||
std::cout << j << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
{"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"}
|
||||
```
|
||||
|
||||
Example: deserialize a `person` from JSON with `from_json`
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
namespace ns
|
||||
{
|
||||
// a simple struct to model a person
|
||||
struct person
|
||||
{
|
||||
std::string name;
|
||||
std::string address;
|
||||
int age;
|
||||
};
|
||||
} // namespace ns
|
||||
|
||||
namespace ns
|
||||
{
|
||||
void from_json(const json& j, person& p)
|
||||
{
|
||||
j.at("name").get_to(p.name);
|
||||
j.at("address").get_to(p.address);
|
||||
j.at("age").get_to(p.age);
|
||||
}
|
||||
} // namespace ns
|
||||
|
||||
int main()
|
||||
{
|
||||
json j;
|
||||
j["name"] = "Ned Flanders";
|
||||
j["address"] = "744 Evergreen Terrace";
|
||||
j["age"] = 60;
|
||||
|
||||
auto p = j.get<ns::person>();
|
||||
|
||||
std::cout << p.name << " (" << p.age << ") lives in " << p.address << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
Ned Flanders (60) lives in 744 Evergreen Terrace
|
||||
```
|
||||
|
||||
## Simplify your life with macros
|
||||
|
||||
If you just want to serialize/deserialize some structs, the `to_json`/`from_json` functions can be a lot of boilerplate.
|
||||
@@ -96,32 +187,54 @@ There are several macros to make your life easier as long as you want to use a J
|
||||
|
||||
For all the macros, the first parameter is the name of the class/struct. The `DERIVED_TYPE` macros require a second parameter of a base class. All the remaining parameters name the member variables. The `WITH_NAMES` macros require a JSON name before each of the variables.
|
||||
|
||||
| Need access to private members | Need only de-serialization | Allow missing values when de-serializing | macro |
|
||||
| ------------------------------ | -------------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| | | | [**NLOHMANN_DEFINE_TYPE_INTRUSIVE**](https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/index.md) |
|
||||
| | | | [**NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT**](https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/index.md) |
|
||||
| | | | [**NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE**](https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/index.md) |
|
||||
| | | | [**NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE**](https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/index.md) |
|
||||
| | | | [**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) |
|
||||
```
|
||||
flowchart TD
|
||||
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?"}
|
||||
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?"}
|
||||
G --> H
|
||||
H -->|"yes"| I["...ONLY_SERIALIZE"]
|
||||
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?"}
|
||||
K --> M
|
||||
L --> M
|
||||
M -->|"yes"| N["...WITH_NAMES"]
|
||||
M -->|"no"| O["done"]
|
||||
```
|
||||
|
||||
| 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) |
|
||||
| | | | [**NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT**](https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/index.md) |
|
||||
| | | | [**NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE**](https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/index.md) |
|
||||
| | | | [**NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE**](https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/index.md) |
|
||||
| | | | [**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) |
|
||||
|
||||
For *derived* classes and structs, use the following macros
|
||||
|
||||
| Need access to private members | Need only de-serialization | Allow missing values when de-serializing | macro |
|
||||
| ------------------------------ | -------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| | | | [**NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE**](https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/index.md) |
|
||||
| | | | [**NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT**](https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/index.md) |
|
||||
| | | | [**NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE**](https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/index.md) |
|
||||
| | | | [**NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE**](https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/index.md) |
|
||||
| | | | [**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) |
|
||||
| Need access to private members | Need only serialization | Allow missing values when de-serializing | macro |
|
||||
| ------------------------------ | ----------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| | | | [**NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE**](https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/index.md) |
|
||||
| | | | [**NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT**](https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/index.md) |
|
||||
| | | | [**NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE**](https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/index.md) |
|
||||
| | | | [**NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE**](https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/index.md) |
|
||||
| | | | [**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) |
|
||||
|
||||
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.
|
||||
|
||||
Example
|
||||
Example: using the `NLOHMANN_DEFINE_TYPE_*` macros
|
||||
|
||||
The `to_json`/`from_json` functions for the `person` struct above can be created with:
|
||||
|
||||
@@ -222,6 +335,14 @@ There is currently no `NLOHMANN_DEFINE_TYPE_*`-style macro for types that are no
|
||||
|
||||
This requires a bit more advanced technique. But first, let us see how this conversion mechanism works:
|
||||
|
||||
```
|
||||
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"]
|
||||
```
|
||||
|
||||
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):
|
||||
@@ -275,7 +396,73 @@ Use [`NLOHMANN_JSON_NAMESPACE_BEGIN`](https://json.nlohmann.me/api/macros/nlohma
|
||||
|
||||
## How can I use `get()` for non-default constructible/non-copyable types?
|
||||
|
||||
There is a way if your type is [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible). You will need to specialize the `adl_serializer` as well, but with a special `from_json` overload:
|
||||
For a type that is not [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible) but is otherwise an ordinary value type, specialize `adl_serializer` with a `from_json` overload that returns the value instead of writing into a reference:
|
||||
|
||||
Example: `get()` for a non-default-constructible type
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
namespace ns
|
||||
{
|
||||
// a simple struct to model a person (not default constructible)
|
||||
struct person
|
||||
{
|
||||
person(std::string n, std::string a, int aa)
|
||||
: name(std::move(n)), address(std::move(a)), age(aa)
|
||||
{}
|
||||
|
||||
std::string name;
|
||||
std::string address;
|
||||
int age;
|
||||
};
|
||||
} // namespace ns
|
||||
|
||||
namespace nlohmann
|
||||
{
|
||||
template <>
|
||||
struct adl_serializer<ns::person>
|
||||
{
|
||||
static ns::person from_json(const json& j)
|
||||
{
|
||||
return {j.at("name"), j.at("address"), j.at("age")};
|
||||
}
|
||||
|
||||
// Here's the catch! You must provide a to_json method! Otherwise, you
|
||||
// will not be able to convert person to json, since you fully
|
||||
// specialized adl_serializer on that type
|
||||
static void to_json(json& j, ns::person p)
|
||||
{
|
||||
j["name"] = p.name;
|
||||
j["address"] = p.address;
|
||||
j["age"] = p.age;
|
||||
}
|
||||
};
|
||||
} // namespace nlohmann
|
||||
|
||||
int main()
|
||||
{
|
||||
json j;
|
||||
j["name"] = "Ned Flanders";
|
||||
j["address"] = "744 Evergreen Terrace";
|
||||
j["age"] = 60;
|
||||
|
||||
auto p = j.get<ns::person>();
|
||||
|
||||
std::cout << p.name << " (" << p.age << ") lives in " << p.address << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
Ned Flanders (60) lives in 744 Evergreen Terrace
|
||||
```
|
||||
|
||||
The same technique also works if your type is not copyable, as long as it is [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
|
||||
|
||||
```
|
||||
struct move_only_type {
|
||||
@@ -331,13 +518,7 @@ json any_to_json(const std::any& a) {
|
||||
|
||||
## Why does serializing a `std::map`/`std::unordered_map` with non-string keys produce an array?
|
||||
|
||||
A `std::map`/`std::unordered_map` whose key type is not string-like (e.g., `std::map<int, std::string>`) is serialized as a JSON *array* of 2-element `[key, value]` arrays, not as a JSON object -- JSON object keys must be strings, so the library cannot represent an integer-keyed map as an object.
|
||||
|
||||
```
|
||||
std::map<int, std::string> m{{1, "one"}, {2, "two"}};
|
||||
json j = m;
|
||||
// j is [[1,"one"],[2,"two"]], not {"1":"one","2":"two"}
|
||||
```
|
||||
A `std::map`/`std::unordered_map` whose key type is not string-like (e.g., `std::map<int, std::string>`) cannot be serialized as a JSON object, because JSON object keys must be strings. See [Converting maps with non-string keys](https://json.nlohmann.me/features/types/#converting-maps-with-non-string-keys) in the types article for what the library does instead.
|
||||
|
||||
## Why does `std::wstring` convert or dump incorrectly?
|
||||
|
||||
@@ -380,7 +561,7 @@ struct less_than_32_serializer {
|
||||
Be **very** careful when reimplementing your serializer, you can stack overflow if you don't pay attention:
|
||||
|
||||
```
|
||||
template <typename T, void>
|
||||
template <typename T, typename = void>
|
||||
struct bad_serializer
|
||||
{
|
||||
template <typename BasicJsonType>
|
||||
@@ -398,3 +579,10 @@ struct bad_serializer
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [Converting values](https://json.nlohmann.me/features/conversions/index.md) - the general overview of `get`/`get_to` and implicit conversions
|
||||
- [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
|
||||
Reference in new issue
Block a user