JsonObject.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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/StringBuilder.h"
  8. using namespace ArduinoJson::Internals;
  9. JsonValue JsonObject::operator[](char const* key)
  10. {
  11. JsonNode* node = getOrCreateNodeAt(key);
  12. return JsonValue(node);
  13. }
  14. void JsonObject::remove(char const* key)
  15. {
  16. JsonNode* lastChild = 0;
  17. for (JsonNodeIterator it = beginChildren(); it != endChildren(); ++it)
  18. {
  19. const char* childKey = it->content.asKey.key;
  20. if (!strcmp(childKey, key))
  21. {
  22. removeChildAfter(*it, lastChild);
  23. }
  24. lastChild = *it;
  25. }
  26. }
  27. JsonObject JsonObject::createNestedObject(char const* key)
  28. {
  29. JsonNode* node = getOrCreateNodeAt(key);
  30. if (node)
  31. {
  32. node->type = JSON_OBJECT;
  33. node->content.asContainer.child = 0;
  34. node->content.asContainer.buffer = _node->content.asContainer.buffer;
  35. }
  36. return JsonObject(node);
  37. }
  38. JsonNode* JsonObject::getOrCreateNodeAt(const char* key)
  39. {
  40. if (!checkNodeType(JSON_OBJECT)) return 0;
  41. for (JsonNodeIterator it = beginChildren(); it != endChildren(); ++it)
  42. {
  43. const char* childKey = it->content.asKey.key;
  44. if (!strcmp(childKey, key))
  45. return it->content.asKey.value;
  46. }
  47. JsonNode* newValueNode = createNode(JSON_UNDEFINED);
  48. if (!newValueNode) return 0;
  49. JsonNode* newKeyNode = createNode(JSON_KEY);
  50. if (!newKeyNode) return 0;
  51. newKeyNode->content.asKey.key = key;
  52. newKeyNode->content.asKey.value = newValueNode;
  53. addChild(newKeyNode);
  54. return newValueNode;
  55. }