JsonHashTable.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Arduino JSON library
  3. * Benoit Blanchon 2014 - MIT License
  4. */
  5. #include <string.h> // for strcmp()
  6. #include "JsonArray.h"
  7. #include "JsonHashTable.h"
  8. using namespace ArduinoJson::Parser;
  9. JsonHashTable::JsonHashTable(char* json, jsmntok_t* tokens)
  10. : JsonObjectBase(json, tokens)
  11. {
  12. if (tokens == 0 || tokens[0].type != JSMN_OBJECT)
  13. makeInvalid();
  14. }
  15. /*
  16. * Returns the token for the value associated with the specified key
  17. */
  18. jsmntok_t* JsonHashTable::getToken(const char* desiredKey)
  19. {
  20. // sanity check
  21. if (json == 0 || tokens == 0 || desiredKey == 0)
  22. return 0;
  23. // skip first token, it's the whole object
  24. jsmntok_t* currentToken = tokens + 1;
  25. // scan each keys
  26. for (int i = 0; i < tokens[0].size / 2 ; i++)
  27. {
  28. // get key token string
  29. char* key = getStringFromToken(currentToken);
  30. // compare with desired name
  31. if (strcmp(desiredKey, key) == 0)
  32. {
  33. // return the value token that follows the key token
  34. return currentToken + 1;
  35. }
  36. // move forward: key + value + nested tokens
  37. currentToken += 2 + getNestedTokenCount(currentToken + 1);
  38. }
  39. // nothing found, return NULL
  40. return 0;
  41. }
  42. bool JsonHashTable::containsKey(const char* key)
  43. {
  44. return getToken(key) != 0;
  45. }
  46. JsonArray JsonHashTable::getArray(const char* key)
  47. {
  48. return JsonArray(json, getToken(key));
  49. }
  50. bool JsonHashTable::getBool(const char* key)
  51. {
  52. return getBoolFromToken(getToken(key));
  53. }
  54. double JsonHashTable::getDouble(const char* key)
  55. {
  56. return getDoubleFromToken(getToken(key));
  57. }
  58. JsonHashTable JsonHashTable::getHashTable(const char* key)
  59. {
  60. return JsonHashTable(json, getToken(key));
  61. }
  62. long JsonHashTable::getLong(const char* key)
  63. {
  64. return getLongFromToken(getToken(key));
  65. }
  66. char* JsonHashTable::getString(const char* key)
  67. {
  68. return getStringFromToken(getToken(key));
  69. }