JsonHashTable.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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(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. JsonArray JsonHashTable::getArray(char* key)
  42. {
  43. return JsonArray(json, getToken(key));
  44. }
  45. JsonHashTable JsonHashTable::getHashTable(char* key)
  46. {
  47. return JsonHashTable(json, getToken(key));
  48. }
  49. long JsonHashTable::getLong(char* key)
  50. {
  51. return getLongFromToken(getToken(key));
  52. }
  53. char* JsonHashTable::getString(char* key)
  54. {
  55. return getStringFromToken(getToken(key));
  56. }