Files
ArduinoJson/ArduinoJsonParser.cpp

90 lines
1.8 KiB
C++
Raw Normal View History

2014-01-10 20:19:58 +01:00
/*
* malloc-free JSON parser for Arduino
* Benoit Blanchon 2014
* MIT License
*/
#include "ArduinoJsonParser.h"
2014-01-11 10:45:14 +01:00
int JsonObjectBase::getNestedTokenCounts(int tokenIndex)
2014-01-10 21:44:44 +01:00
{
int count = 0;
for (int i = 0; i < tokens[tokenIndex].size; i++)
{
count += 1 + getNestedTokenCounts(tokenIndex + 1 + i);
}
return count;
}
2014-01-11 10:45:14 +01:00
bool JsonParserBase::parse(char* jsonString)
2014-01-10 20:19:58 +01:00
{
buffer = jsonString;
2014-01-10 20:50:29 +01:00
if (JSMN_SUCCESS != jsmn_parse(&parser, jsonString, tokens, maxTokenCount))
return false;
2014-01-10 20:19:58 +01:00
// Add null termination to each token
2014-01-10 21:44:44 +01:00
for (int i = 1; i < parser.toknext; i++)
2014-01-10 20:19:58 +01:00
{
buffer[tokens[i].end] = 0;
}
return true;
}
2014-01-11 11:06:33 +01:00
jsmntok_t* JsonHashTable::getToken(char* name)
2014-01-11 10:45:14 +01:00
{
// skip first token, it's the whole object
int currentToken = 1;
// Scan each keys
for (int i = 0; i < tokens[0].size / 2 ; i++)
2014-01-10 20:19:58 +01:00
{
// Get key token string
2014-01-11 10:45:14 +01:00
char* key = json + tokens[currentToken].start;
2014-01-10 20:19:58 +01:00
// Compare with desired name
if (strcmp(name, key) == 0)
{
2014-01-11 11:06:33 +01:00
return &tokens[currentToken + 1];
2014-01-10 20:19:58 +01:00
}
2014-01-10 21:44:44 +01:00
2014-01-11 10:45:14 +01:00
// move forward: key + value + nested tokens
currentToken += 2 + getNestedTokenCounts(currentToken + 1);
2014-01-10 20:19:58 +01:00
}
2014-01-11 10:45:14 +01:00
return NULL;
}
2014-01-10 21:44:44 +01:00
2014-01-11 11:06:33 +01:00
JsonArray JsonHashTable::getArray(char* key)
{
jsmntok_t* token = getToken(key);
return JsonArray(json, token);
}
2014-01-11 11:18:53 +01:00
jsmntok_t* JsonArray::getToken(int index)
2014-01-10 21:44:44 +01:00
{
2014-01-11 10:57:55 +01:00
if (json == NULL) return NULL;
if (tokens == NULL) return NULL;
if (index < 0) return NULL;
if (index >= tokens[0].size) return NULL;
2014-01-10 21:44:44 +01:00
2014-01-11 10:57:55 +01:00
// skip first token, it's the whole object
int currentToken = 1;
2014-01-10 21:44:44 +01:00
2014-01-11 10:57:55 +01:00
for (int i = 0; i < index; i++)
{
// move forward: current + nested tokens
currentToken += 1 + getNestedTokenCounts(currentToken);
2014-01-10 21:44:44 +01:00
}
2014-01-10 20:50:29 +01:00
2014-01-11 11:18:53 +01:00
return &tokens[currentToken];
2014-01-10 20:50:29 +01:00
}
2014-01-11 11:18:53 +01:00
JsonArray JsonArray::getArray(int index)
{
jsmntok_t* token = getToken(index);
return JsonArray(json, token);
}