Issue10.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright Benoit Blanchon 2014
  2. // MIT License
  3. //
  4. // Arduino JSON library
  5. // https://github.com/bblanchon/ArduinoJson
  6. #include <gtest/gtest.h>
  7. #include <ArduinoJson/JsonArray.hpp>
  8. #include <ArduinoJson/JsonObject.hpp>
  9. #include <ArduinoJson/JsonValue.hpp>
  10. #include <ArduinoJson/StaticJsonBuffer.hpp>
  11. using namespace ArduinoJson;
  12. struct Person {
  13. int id;
  14. char name[32];
  15. };
  16. class Issue10 : public testing::Test {
  17. protected:
  18. virtual void SetUp() {
  19. Person boss;
  20. boss.id = 1;
  21. strcpy(boss.name, "Jeff");
  22. Person employee;
  23. employee.id = 2;
  24. strcpy(employee.name, "John");
  25. persons[0] = boss;
  26. persons[1] = employee;
  27. }
  28. void checkJsonString(JsonContainer &p) {
  29. char buffer[256];
  30. p.printTo(buffer, sizeof(buffer));
  31. EXPECT_STREQ("[{\"id\":1,\"name\":\"Jeff\"},{\"id\":2,\"name\":\"John\"}]",
  32. buffer);
  33. }
  34. void nodeCountMustBe(int expected) { EXPECT_EQ(expected, json.size()); }
  35. Person persons[2];
  36. StaticJsonBuffer<20> json;
  37. };
  38. TEST_F(Issue10, PopulateArrayByAddingAnObject) {
  39. JsonArray array = json.createArray();
  40. for (int i = 0; i < 2; i++) {
  41. JsonObject object = json.createObject();
  42. object["id"] = persons[i].id;
  43. object["name"] = persons[i].name;
  44. array.add(object); // <- adds a reference to an existing objet (creates 2
  45. // extra proxy nodes)
  46. }
  47. checkJsonString(array);
  48. nodeCountMustBe(15);
  49. }
  50. TEST_F(Issue10, PopulateArrayByCreatingNestedObjects) {
  51. JsonArray array = json.createArray();
  52. for (int i = 0; i < 2; i++) {
  53. JsonObject object = array.createNestedObject();
  54. object["id"] = persons[i].id;
  55. object["name"] = persons[i].name;
  56. }
  57. checkJsonString(array);
  58. nodeCountMustBe(11);
  59. }