JsonObjectBase.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Arduino JSON library
  3. * Benoit Blanchon 2014 - MIT License
  4. */
  5. #include "JsonObjectBase.h"
  6. #include <string.h> // for strcmp
  7. using namespace ArduinoJson::Generator;
  8. using namespace ArduinoJson::Internals;
  9. JsonValue JsonObjectBase::nullValue;
  10. size_t JsonObjectBase::printTo(Print& p) const
  11. {
  12. size_t n = 0;
  13. n += p.write('{');
  14. // NB: the code has been optimized for a small size on a 8-bit AVR
  15. const KeyValuePair* current = items;
  16. for (int i = count; i > 0; i--)
  17. {
  18. n += EscapedString::printTo(current->key, p);
  19. n += p.write(':');
  20. n += current->value.printTo(p);
  21. current++;
  22. if (i > 1)
  23. {
  24. n += p.write(',');
  25. }
  26. }
  27. n += p.write('}');
  28. return n;
  29. }
  30. JsonObjectBase::KeyValuePair* JsonObjectBase::getMatchingPair(JsonKey key) const
  31. {
  32. KeyValuePair* p = items;
  33. for (int i = count; i > 0; --i)
  34. {
  35. if (!strcmp(p->key, key))
  36. return p;
  37. p++;
  38. }
  39. return 0;
  40. }
  41. JsonValue& JsonObjectBase::operator[](JsonKey key)
  42. {
  43. KeyValuePair* match = getMatchingPair(key);
  44. if (match)
  45. return match->value;
  46. JsonValue* value;
  47. if (count < capacity)
  48. {
  49. items[count].key = key;
  50. value = &items[count].value;
  51. count++;
  52. }
  53. else
  54. {
  55. value = &nullValue;
  56. }
  57. value->reset();
  58. return *value;
  59. }
  60. bool JsonObjectBase::containsKey(JsonKey key) const
  61. {
  62. return getMatchingPair(key) != 0;
  63. }
  64. void JsonObjectBase::remove(JsonKey key)
  65. {
  66. KeyValuePair* match = getMatchingPair(key);
  67. if (match == 0) return;
  68. *match = items[--count];
  69. }