-
Notifications
You must be signed in to change notification settings - Fork 1
/
JsonObjectBase.cpp
63 lines (46 loc) · 1.3 KB
/
JsonObjectBase.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
* malloc-free JSON parser for Arduino
* Benoit Blanchon 2014
* MIT License
*/
#include "JsonObjectBase.h"
#include <stdlib.h> // for strtol, strtod
int JsonObjectBase::getNestedTokenCount(jsmntok_t* token)
{
int count = 0;
for (int i = 0; i < token->size; i++)
{
count += 1 + getNestedTokenCount(token + 1 + i);
}
return count;
}
bool JsonObjectBase::getBoolFromToken(jsmntok_t* token)
{
if (token->type != JSMN_PRIMITIVE) return 0;
// "true"
if (json[token->start] == 't') return true;
// "false"
if (json[token->start] == 'f') return false;
// "null"
if (json[token->start] == 'n') return false;
// number
return strtol(json + token->start, 0, 0) != 0;
}
double JsonObjectBase::getDoubleFromToken(jsmntok_t* token)
{
if (token == 0 || token->type != JSMN_PRIMITIVE) return 0;
return strtod(json + token->start, 0);
}
long JsonObjectBase::getLongFromToken(jsmntok_t* token)
{
if (token == 0 || token->type != JSMN_PRIMITIVE) return 0;
return strtol(json + token->start, 0, 0);
}
char* JsonObjectBase::getStringFromToken(jsmntok_t* token)
{
if (token == 0 || token->type != JSMN_PRIMITIVE && token->type != JSMN_STRING)
return 0;
// add null terminator to the string
json[token->end] = 0;
return json + token->start;
}