JsonObject.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. JsonArray JsonObject::createNestedArray(char const* key)
  28. {
  29. JsonNode* node = createContainerNodeAt(key, JSON_ARRAY);
  30. return JsonArray(node);
  31. }
  32. JsonObject JsonObject::createNestedObject(char const* key)
  33. {
  34. JsonNode* node = createContainerNodeAt(key, JSON_OBJECT);
  35. return JsonObject(node);
  36. }
  37. JsonNode* JsonObject::getOrCreateNodeAt(const char* key)
  38. {
  39. if (!checkNodeType(JSON_OBJECT)) return 0;
  40. for (JsonNodeIterator it = beginChildren(); it != endChildren(); ++it)
  41. {
  42. const char* childKey = it->content.asKey.key;
  43. if (!strcmp(childKey, key))
  44. return it->content.asKey.value;
  45. }
  46. JsonNode* newValueNode = createNode(JSON_UNDEFINED);
  47. if (!newValueNode) return 0;
  48. JsonNode* newKeyNode = createNode(JSON_KEY);
  49. if (!newKeyNode) return 0;
  50. newKeyNode->content.asKey.key = key;
  51. newKeyNode->content.asKey.value = newValueNode;
  52. addChild(newKeyNode);
  53. return newValueNode;
  54. }
  55. JsonNode* JsonObject::createContainerNodeAt(char const* key, JsonNodeType type)
  56. {
  57. JsonNode* node = getOrCreateNodeAt(key);
  58. if (!node) return 0;
  59. node->type = type;
  60. node->content.asContainer.child = 0;
  61. node->content.asContainer.buffer = _node->content.asContainer.buffer;
  62. return node;
  63. }