This is a lightweight component that wraps Niels Lohmann's excellent JSON library.
It downloads the single-header version of the library with CMake (using FetchContent). It works for ESP-IDF but can be used for desktop C++ development too.
Add a dependency with idf.py add-dependency mittelab/nlohmann-json
, and then you can use it with
C++
#include <nlohmann/json.hpp>
This is a header wrapper that defines some custom macros (see below). If you need the original header for some reason, include
C++
#include <nlohmann/json_impl.hpp>
Assume you have checked out this repo at $PROJ/thirdparty/nlohmann-json
. Then in your root CMakeLists.txt
, add
Cmake
list(APPEND EXTRA_COMPONENT_DIRS "$PROJ/thirdparty/nlohmann-json")
# include($ENV{IDF_PATH}/tools/cmake/project.cmake)
# project(...)
In the components that need to use this library, make sure to specify nlohmann-json
as CMake dependency:
Cmake
idf_component_register(
SRCS ${SOURCES}
REQUIRES
nlohmann-json
)
Assume you have checked out this repo at $PROJ/thirdparty/nlohmann-json
. Then in your CMakeLists.txt
, add
Cmake
add_subdirectory($PROJ/thirdparty/nlohmann-json/nlohmann-json)
# Your target setup goes here, then
target_link_libraries($YOUR_TARGET nlohmann-json)
target_include_directories($YOUR_TARGET PRIVATE $<TARGET_PROPERTY:nlohmann-json,INTERFACE_INCLUDE_DIRECTORIES>)
By default, including <nlohmann/json.hpp>
sets the following macros:
JSON_NO_IO
<iostream>
headers, which increase significantly the size of the app.JSON_NOEXCEPTION
JSON_DISABLE_ENUM_SERIALIZATION
If you need to change the macro configurations, define your own json.hpp
header with your custom macros and include directly <nlohmann/json_impl.hpp>
.
idf.py add-dependency "mittelab/nlohmann-json^3.11.3"