Skip to content

Commit ddc2f59

Browse files
create msgs with json
1 parent e4670a8 commit ddc2f59

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

include/mav/Message.h

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@
3939
#include <array>
4040
#include <utility>
4141
#include <variant>
42+
43+
#include <nlohmann/json.hpp>
44+
4245
#include "MessageDefinition.h"
4346
#include "utils.h"
4447
#include "picosha2/picosha2.h"
@@ -284,6 +287,38 @@ namespace mav {
284287
return *this;
285288
}
286289

290+
Message& operator()(const nlohmann::json &j) {
291+
for (auto it = j.begin(); it != j.end(); ++it) {
292+
const std::string& key = it.key();
293+
const auto& value = it.value();
294+
295+
if (value.is_string()) {
296+
setFromNativeTypeVariant(key, value.get<std::string>());
297+
}
298+
else if (value.is_number_integer()) {
299+
setFromNativeTypeVariant(key, value.get<int>());
300+
}
301+
else if (value.is_number_unsigned()) {
302+
setFromNativeTypeVariant(key, value.get<unsigned int>());
303+
}
304+
else if (value.is_number_float()) {
305+
setFromNativeTypeVariant(key, value.get<float>());
306+
}
307+
else if (value.is_boolean()) {
308+
setFromNativeTypeVariant(key, value.get<bool>());
309+
}
310+
else if (value.is_array()) {
311+
// NOTE: choose actual expected vector element type
312+
setFromNativeTypeVariant(key, value.get<std::vector<float>>());
313+
}
314+
else {
315+
std::cerr << "Unsupported JSON type: " << key << std::endl;
316+
}
317+
}
318+
return *this;
319+
}
320+
321+
287322
template <typename T>
288323
Message& set(const std::string &field_key, const T &v, int array_index = 0) {
289324
auto field = _message_definition->fieldForName(field_key);

0 commit comments

Comments
 (0)