JsonArray.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * malloc-free JSON parser for Arduino
  3. * Benoit Blanchon 2014 - MIT License
  4. */
  5. #include "JsonArray.h"
  6. #include "JsonHashTable.h"
  7. JsonArray::JsonArray(char* json, jsmntok_t* tokens)
  8. : JsonObjectBase(json, tokens)
  9. {
  10. if (tokens[0].type != JSMN_ARRAY)
  11. makeInvalid();
  12. }
  13. /*
  14. * Returns the token for the value at the specified index
  15. */
  16. jsmntok_t* JsonArray::getToken(int index)
  17. {
  18. // sanity check
  19. if (json == 0 || tokens == 0 || index < 0 || index >= tokens[0].size)
  20. return 0;
  21. // skip first token, it's the whole object
  22. jsmntok_t* currentToken = tokens + 1;
  23. // skip all tokens before the specified index
  24. for (int i = 0; i < index; i++)
  25. {
  26. // move forward: current + nested tokens
  27. currentToken += 1 + getNestedTokenCount(currentToken);
  28. }
  29. return currentToken;
  30. }
  31. JsonArray JsonArray::getArray(int index)
  32. {
  33. return JsonArray(json, getToken(index));
  34. }
  35. JsonHashTable JsonArray::getHashTable(int index)
  36. {
  37. return JsonHashTable(json, getToken(index));
  38. }
  39. long JsonArray::getLong(int index)
  40. {
  41. return getLongFromToken(getToken(index));
  42. }
  43. char* JsonArray::getString(int index)
  44. {
  45. return getStringFromToken(getToken(index));
  46. }