JsonArray.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. double JsonArray::getDouble(int index)
  36. {
  37. return getDoubleFromToken(getToken(index));
  38. }
  39. JsonHashTable JsonArray::getHashTable(int index)
  40. {
  41. return JsonHashTable(json, getToken(index));
  42. }
  43. long JsonArray::getLong(int index)
  44. {
  45. return getLongFromToken(getToken(index));
  46. }
  47. char* JsonArray::getString(int index)
  48. {
  49. return getStringFromToken(getToken(index));
  50. }