JsonObjectBase.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * malloc-free JSON parser for Arduino
  3. * Benoit Blanchon 2014
  4. * MIT License
  5. */
  6. #include "JsonObjectBase.h"
  7. #include <stdlib.h> // for strtol, strtod
  8. int JsonObjectBase::getNestedTokenCount(jsmntok_t* token)
  9. {
  10. int count = 0;
  11. for (int i = 0; i < token->size; i++)
  12. {
  13. count += 1 + getNestedTokenCount(token + 1 + i);
  14. }
  15. return count;
  16. }
  17. bool JsonObjectBase::getBoolFromToken(jsmntok_t* token)
  18. {
  19. if (token->type != JSMN_PRIMITIVE) return 0;
  20. // "true"
  21. if (json[token->start] == 't') return true;
  22. // "false"
  23. if (json[token->start] == 'f') return false;
  24. // "null"
  25. if (json[token->start] == 'n') return false;
  26. // number
  27. return strtol(json + token->start, 0, 0) != 0;
  28. }
  29. double JsonObjectBase::getDoubleFromToken(jsmntok_t* token)
  30. {
  31. if (token == 0 || token->type != JSMN_PRIMITIVE) return 0;
  32. return strtod(json + token->start, 0);
  33. }
  34. long JsonObjectBase::getLongFromToken(jsmntok_t* token)
  35. {
  36. if (token == 0 || token->type != JSMN_PRIMITIVE) return 0;
  37. return strtol(json + token->start, 0, 0);
  38. }
  39. char* JsonObjectBase::getStringFromToken(jsmntok_t* token)
  40. {
  41. if (token == 0 || token->type != JSMN_PRIMITIVE && token->type != JSMN_STRING)
  42. return 0;
  43. // add null terminator to the string
  44. json[token->end] = 0;
  45. return json + token->start;
  46. }