JsonObject.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "JsonObject.h"
  2. #include <string.h> // for strcmp
  3. #include "JsonBuffer.h"
  4. #include "JsonValue.h"
  5. #include "Internals/EscapedString.h"
  6. #include "Internals/JsonNode.h"
  7. #include "Internals/JsonNodeSerializer.h"
  8. #include "Internals/StringBuilder.h"
  9. using namespace ArduinoJson::Internals;
  10. JsonValue JsonObject::operator[](char const* key)
  11. {
  12. JsonNode* node = getOrCreateNodeAt(key);
  13. return JsonValue(node);
  14. }
  15. void JsonObject::remove(char const* key)
  16. {
  17. JsonNode* lastChild = 0;
  18. for (JsonNodeIterator it = beginChildren(); it != endChildren(); ++it)
  19. {
  20. const char* childKey = it->content.asKey.key;
  21. if (!strcmp(childKey, key))
  22. {
  23. removeChildAfter(*it, lastChild);
  24. }
  25. lastChild = *it;
  26. }
  27. }
  28. JsonNode* JsonObject::getOrCreateNodeAt(const char* key)
  29. {
  30. if (!checkNodeType(JSON_OBJECT)) return 0;
  31. JsonNode* lastChild = 0;
  32. for (JsonNodeIterator it = beginChildren(); it != endChildren(); ++it)
  33. {
  34. const char* childKey = it->content.asKey.key;
  35. if (!strcmp(childKey, key))
  36. return it->content.asKey.value;
  37. lastChild = *it;
  38. }
  39. JsonNode* newValueNode = createNode(JSON_UNDEFINED);
  40. if (!newValueNode) return 0;
  41. JsonNode* newKeyNode = createNode(JSON_KEY);
  42. if (!newKeyNode) return 0;
  43. newKeyNode->content.asKey.key = key;
  44. newKeyNode->content.asKey.value = newValueNode;
  45. insertChildAfter(newKeyNode, lastChild);
  46. return newValueNode;
  47. }