JsonValue.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. * Arduino JSON library
  3. * Benoit Blanchon 2014 - MIT License
  4. */
  5. #include <stdlib.h> // for strtol, strtod
  6. #include <string.h> // for strcmp()
  7. #include "JsonArray.h"
  8. #include "JsonHashTable.h"
  9. #include "JsonValue.h"
  10. using namespace ArduinoJson::Parser;
  11. JsonValue::operator bool()
  12. {
  13. if (tokens == 0 || tokens->type != JSMN_PRIMITIVE) return 0;
  14. // "true"
  15. if (json[tokens->start] == 't') return true;
  16. // "false"
  17. if (json[tokens->start] == 'f') return false;
  18. // "null"
  19. if (json[tokens->start] == 'n') return false;
  20. // number
  21. return strtol(json + tokens->start, 0, 0) != 0;
  22. }
  23. JsonValue::operator double()
  24. {
  25. if (tokens == 0 || tokens->type != JSMN_PRIMITIVE) return 0;
  26. return strtod(json + tokens->start, 0);
  27. }
  28. JsonValue::operator long()
  29. {
  30. if (tokens == 0 || tokens->type != JSMN_PRIMITIVE) return 0;
  31. return strtol(json + tokens->start, 0, 0);
  32. }
  33. JsonValue::operator char*()
  34. {
  35. if (tokens == 0 || tokens->type != JSMN_PRIMITIVE && tokens->type != JSMN_STRING)
  36. return 0;
  37. // add null terminator to the string
  38. json[tokens->end] = 0;
  39. return json + tokens->start;
  40. }
  41. JsonValue::operator JsonArray()
  42. {
  43. return tokens->type != JSMN_ARRAY
  44. ? JsonArray(*this)
  45. : JsonArray();
  46. }
  47. JsonValue::operator JsonHashTable()
  48. {
  49. return tokens->type != JSMN_OBJECT
  50. ? JsonHashTable(*this)
  51. : JsonHashTable();
  52. }
  53. /*
  54. * Returns the token for the value associated with the specified key
  55. */
  56. JsonValue JsonValue::operator [](const char* desiredKey)
  57. {
  58. // sanity check
  59. if (!json || !desiredKey || tokens->type != JSMN_OBJECT)
  60. return JsonValue();
  61. // skip first token, it's the whole object
  62. jsmntok_t* currentToken = tokens + 1;
  63. // scan each keys
  64. for (int i = 0; i < tokens[0].size / 2; i++)
  65. {
  66. // get key token string
  67. char* key = JsonValue(json, currentToken);
  68. // compare with desired name
  69. if (strcmp(desiredKey, key) == 0)
  70. {
  71. // return the value token that follows the key token
  72. return JsonValue(json, currentToken + 1);
  73. }
  74. // move forward: key + value + nested tokens
  75. currentToken += 2 + getNestedTokenCount(currentToken + 1);
  76. }
  77. // nothing found, return NULL
  78. return JsonValue();
  79. }