JsonHashTable.cpp 1.8 KB

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