// ArduinoJson - https://arduinojson.org // Copyright © 2014-2024, Benoit BLANCHON // MIT License #include #include #include #include #include #include namespace ArduinoJson { template struct Converter> { static void toJson(const std::vector& src, JsonVariant dst) { JsonArray array = dst.to(); for (T item : src) array.add(item); } static std::vector fromJson(JsonVariantConst src) { std::vector dst; for (T item : src.as()) dst.push_back(item); return dst; } static bool checkJson(JsonVariantConst src) { JsonArrayConst array = src; bool result = array; for (JsonVariantConst item : array) result &= item.is(); return result; } }; template struct Converter> { static void toJson(const std::array& src, JsonVariant dst) { JsonArray array = dst.to(); for (T item : src) array.add(item); } static std::array fromJson(JsonVariantConst src) { std::array dst; dst.fill(0); size_t idx = 0; for (T item : src.as()) dst[idx++] = item; return dst; } static bool checkJson(JsonVariantConst src) { JsonArrayConst array = src; bool result = array; size_t size = 0; for (JsonVariantConst item : array) { result &= item.is(); size++; } return result && size == N; } }; } // namespace ArduinoJson TEST_CASE("vector") { SECTION("toJson") { std::vector v = {1, 2}; JsonDocument doc; doc.set(v); REQUIRE(doc.as() == "[1,2]"); } SECTION("fromJson") { JsonDocument doc; doc.add(1); doc.add(2); auto v = doc.as>(); REQUIRE(v.size() == 2); CHECK(v[0] == 1); CHECK(v[1] == 2); } SECTION("checkJson") { JsonDocument doc; CHECK(doc.is>() == false); doc.add(1); doc.add(2); CHECK(doc.is>() == true); doc.add("foo"); CHECK(doc.is>() == false); } } TEST_CASE("array") { typedef std::array array_type; SECTION("toJson") { array_type v; v[0] = 1; v[1] = 2; JsonDocument doc; doc.set(v); REQUIRE(doc.as() == "[1,2]"); } SECTION("fromJson") { JsonDocument doc; doc.add(1); doc.add(2); auto v = doc.as(); REQUIRE(v.size() == 2); CHECK(v[0] == 1); CHECK(v[1] == 2); } SECTION("checkJson") { JsonDocument doc; CHECK(doc.is() == false); doc.add(1); CHECK(doc.is() == false); doc.add(2); CHECK(doc.is() == true); doc[0] = "foo"; CHECK(doc.is() == false); } }