Skip to content

Commit 7441d8d

Browse files
Allow a custom "__type" name in the JsonExporter lambda converters (#1255)
The addConverter() overloads that take a user lambda always wrote and registered BT::demangle(typeid(T)) as the JSON "__type", e.g. "geometry_msgs::msg::Pose_<std::allocator<void> >". addConverter<T>() and BT_JSON_CONVERTER already let the user choose the name, but the lambda overloads did not, so such JSON was verbose, compiler-specific, and could not use language-neutral type names. Add an optional trailing type_name parameter (empty keeps the demangled name). The to_json overload writes it in "__type", the from_json overload registers it in the type-name lookup used by fromJson(), in addition to the demangled name, so existing JSON keeps working. A to_json overload taking only (lambda, const char*) forwards with add_type = true; without it, addConverter<T>(f, "Name") would silently convert the string literal to bool add_type. Fixes #877 Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a72d63a commit 7441d8d

2 files changed

Lines changed: 83 additions & 8 deletions

File tree

‎include/behaviortree_cpp/json_export.h‎

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -112,19 +112,33 @@ class JsonExporter
112112
*
113113
* @param to_json the function with signature void(const T&, nlohmann::json&)
114114
* @param add_type if true, add a field called [__type] with the name of the type.
115+
* @param type_name the name stored in [__type]. If empty, the demangled name of T
116+
* is used. Pass the same name to the from_json overload.
115117
*/
116118
template <typename T>
117119
void addConverter(std::function<void(const T&, nlohmann::json&)> to_json,
118-
bool add_type = true);
120+
bool add_type = true, const std::string& type_name = {});
121+
122+
/// Same as above with add_type = true. Without this overload, a string literal
123+
/// passed as second argument would silently convert to add_type.
124+
template <typename T>
125+
void addConverter(std::function<void(const T&, nlohmann::json&)> to_json,
126+
const char* type_name)
127+
{
128+
addConverter<T>(std::move(to_json), true, type_name);
129+
}
119130

120131
/**
121132
* @brief addConverter register a from_json function that converts a json to a type T.
122133
* The conversions from std::vector<T> is automatically registered.
123134
*
124135
* @param from_json the function with signature void(const nlohmann::json&, T&)
136+
* @param type_name an additional name of T accepted in the field [__type]. The
137+
* demangled name of T is always accepted.
125138
*/
126139
template <typename T>
127-
void addConverter(std::function<void(const nlohmann::json&, T&)> from_json);
140+
void addConverter(std::function<void(const nlohmann::json&, T&)> from_json,
141+
const std::string& type_name = {});
128142

129143
private:
130144
using ToJonConverter = std::function<void(const BT::Any&, nlohmann::json&)>;
@@ -196,14 +210,16 @@ inline void JsonExporter::addConverter()
196210
}
197211

198212
template <typename T>
199-
inline void JsonExporter::addConverter(
200-
std::function<void(const T&, nlohmann::json&)> func, bool add_type)
213+
inline void
214+
JsonExporter::addConverter(std::function<void(const T&, nlohmann::json&)> func,
215+
bool add_type, const std::string& type_name)
201216
{
202-
auto converter = [func, add_type](const BT::Any& entry, nlohmann::json& json) {
217+
const std::string name = type_name.empty() ? BT::demangle(typeid(T)) : type_name;
218+
auto converter = [func, add_type, name](const BT::Any& entry, nlohmann::json& json) {
203219
func(entry.cast<T>(), json);
204220
if(add_type)
205221
{
206-
json["__type"] = BT::demangle(typeid(T));
222+
json["__type"] = name;
207223
}
208224
};
209225
//---------------------------------------------
@@ -222,15 +238,19 @@ inline void JsonExporter::addConverter(
222238
}
223239

224240
template <typename T>
225-
inline void
226-
JsonExporter::addConverter(std::function<void(const nlohmann::json&, T&)> func)
241+
inline void JsonExporter::addConverter(
242+
std::function<void(const nlohmann::json&, T&)> func, const std::string& type_name)
227243
{
228244
auto converter = [func](const nlohmann::json& json) -> Entry {
229245
T tmp;
230246
func(json, tmp);
231247
return { BT::Any(tmp), BT::TypeInfo::Create<T>() };
232248
};
233249
type_names_.insert({ BT::demangle(typeid(T)), BT::TypeInfo::Create<T>() });
250+
if(!type_name.empty())
251+
{
252+
type_names_.insert({ type_name, BT::TypeInfo::Create<T>() });
253+
}
234254
from_json_converters_.insert({ typeid(T), std::move(converter) });
235255
//---------------------------------------------
236256
// add the vector<T> converter

‎tests/gtest_json.cpp‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,11 @@ struct Time
4848
uint32_t nsec;
4949
};
5050

51+
struct Temperature
52+
{
53+
double celsius = 0;
54+
};
55+
5156
// NOLINTBEGIN(misc-use-internal-linkage)
5257
BT_JSON_CONVERTER(Vector3D, v)
5358
{
@@ -82,6 +87,16 @@ inline void jsonToTime(const nlohmann::json& j, Time& t)
8287
t.sec = static_cast<uint32_t>(sec);
8388
t.nsec = static_cast<uint32_t>((sec - t.sec) * 1e9);
8489
}
90+
91+
inline void jsonFromTemperature(const Temperature& t, nlohmann::json& j)
92+
{
93+
j["celsius"] = t.celsius;
94+
}
95+
96+
inline void jsonToTemperature(const nlohmann::json& j, Temperature& t)
97+
{
98+
t.celsius = j["celsius"];
99+
}
85100
// NOLINTEND(misc-use-internal-linkage)
86101

87102
} // namespace TestTypes
@@ -177,6 +192,46 @@ TEST_F(JsonTest, CustomTime)
177192
}
178193
}
179194

195+
// Issue #877: the name stored in "__type" can be chosen when registering lambdas
196+
TEST_F(JsonTest, CustomTypeName)
197+
{
198+
BT::JsonExporter& exporter = BT::JsonExporter::get();
199+
const std::string name = "Temperature";
200+
// a string literal as second argument is the type name, not add_type
201+
using TestTypes::Temperature;
202+
exporter.addConverter<Temperature>(TestTypes::jsonFromTemperature, "Temperature");
203+
exporter.addConverter<TestTypes::Temperature>(TestTypes::jsonToTemperature, name);
204+
205+
TestTypes::Temperature temp = { 21.5 };
206+
nlohmann::json json;
207+
ASSERT_TRUE(exporter.toJson(BT::Any(temp), json));
208+
ASSERT_EQ(json["__type"], name);
209+
210+
auto res = exporter.fromJson<TestTypes::Temperature>(json);
211+
ASSERT_TRUE(res) << res.error();
212+
ASSERT_EQ(res->celsius, 21.5);
213+
214+
// the demangled name is still accepted
215+
json["__type"] = BT::demangle(typeid(TestTypes::Temperature));
216+
ASSERT_TRUE(exporter.fromJson<TestTypes::Temperature>(json));
217+
218+
// vectors use the same name
219+
std::vector<TestTypes::Temperature> temps = { { 1.5 }, { 2.5 } };
220+
nlohmann::json json_vec;
221+
ASSERT_TRUE(exporter.toJson(BT::Any(temps), json_vec));
222+
ASSERT_EQ(json_vec[1]["__type"], name);
223+
224+
auto res_vec = exporter.fromJson<std::vector<TestTypes::Temperature>>(json_vec);
225+
ASSERT_TRUE(res_vec) << res_vec.error();
226+
ASSERT_EQ(res_vec->size(), 2u);
227+
ASSERT_EQ((*res_vec)[1].celsius, 2.5);
228+
229+
// without a name, the demangled name of the type is used
230+
TestTypes::Time stamp = { 3, 8000000 };
231+
ASSERT_TRUE(exporter.toJson(BT::Any(stamp), json));
232+
ASSERT_EQ(json["__type"], BT::demangle(typeid(TestTypes::Time)));
233+
}
234+
180235
TEST_F(JsonTest, ConvertFromString)
181236
{
182237
TestTypes::Vector3D vect;

0 commit comments

Comments
 (0)