Issue10.cpp 1.7 KB

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