Added missing newline at end-of-file (issue #24)

This commit is contained in:
Benoit Blanchon
2014-09-27 21:24:29 +02:00
parent 18f93b4eb6
commit cc19266470
58 changed files with 3699 additions and 3698 deletions

1
FixEndOfFile.sh Normal file
View File

@ -0,0 +1 @@
find \( -iname '*.cpp' -o -iname '*.h' \) -exec sed -i -e '$a\' {} \;

View File

@ -1,15 +1,15 @@
/* /*
* malloc-free JSON parser for Arduino * malloc-free JSON parser for Arduino
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
// This file is here to help the Arduino IDE find the .cpp files // This file is here to help the Arduino IDE find the .cpp files
#include "JsonGenerator/EscapedString.cpp" #include "JsonGenerator/EscapedString.cpp"
#include "JsonGenerator/IndentedPrint.cpp" #include "JsonGenerator/IndentedPrint.cpp"
#include "JsonGenerator/JsonArrayBase.cpp" #include "JsonGenerator/JsonArrayBase.cpp"
#include "JsonGenerator/JsonObjectBase.cpp" #include "JsonGenerator/JsonObjectBase.cpp"
#include "JsonGenerator/JsonValue.cpp" #include "JsonGenerator/JsonValue.cpp"
#include "JsonGenerator/JsonPrettyPrint.cpp" #include "JsonGenerator/JsonPrettyPrint.cpp"
#include "JsonGenerator/JsonPrintable.cpp" #include "JsonGenerator/JsonPrintable.cpp"
#include "JsonGenerator/StringBuilder.cpp" #include "JsonGenerator/StringBuilder.cpp"

View File

@ -1,7 +1,7 @@
/* /*
* malloc-free JSON parser for Arduino * malloc-free JSON parser for Arduino
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "JsonGenerator/JsonArray.h" #include "JsonGenerator/JsonArray.h"
#include "JsonGenerator/JsonObject.h" #include "JsonGenerator/JsonObject.h"

View File

@ -2,44 +2,44 @@
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "EscapedString.h" #include "EscapedString.h"
using namespace ArduinoJson::Internals; using namespace ArduinoJson::Internals;
static inline char getSpecialChar(char c) static inline char getSpecialChar(char c)
{ {
// Optimized for code size on a 8-bit AVR // Optimized for code size on a 8-bit AVR
const char* p = "\"\"\\\\\bb\ff\nn\rr\tt\0"; const char* p = "\"\"\\\\\bb\ff\nn\rr\tt\0";
while (p[0] && p[0] != c) while (p[0] && p[0] != c)
{ {
p += 2; p += 2;
} }
return p[1]; return p[1];
} }
static inline size_t printCharTo(char c, Print& p) static inline size_t printCharTo(char c, Print& p)
{ {
char specialChar = getSpecialChar(c); char specialChar = getSpecialChar(c);
return specialChar != 0 return specialChar != 0
? p.write('\\') + p.write(specialChar) ? p.write('\\') + p.write(specialChar)
: p.write(c); : p.write(c);
} }
size_t EscapedString::printTo(const char* s, Print& p) size_t EscapedString::printTo(const char* s, Print& p)
{ {
if (!s) return p.print("null"); if (!s) return p.print("null");
size_t n = p.write('\"'); size_t n = p.write('\"');
while (*s) while (*s)
{ {
n += printCharTo(*s++, p); n += printCharTo(*s++, p);
} }
return n + p.write('\"'); return n + p.write('\"');
} }

View File

@ -1,20 +1,20 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "Print.h" #include "Print.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Internals namespace Internals
{ {
class EscapedString class EscapedString
{ {
public: public:
static size_t printTo(const char*, Print&); static size_t printTo(const char*, Print&);
}; };
} }
} }

View File

@ -1,45 +1,45 @@
#include "IndentedPrint.h" #include "IndentedPrint.h"
using namespace ArduinoJson::Generator; using namespace ArduinoJson::Generator;
void IndentedPrint::indent() void IndentedPrint::indent()
{ {
if (level < MAX_LEVEL) if (level < MAX_LEVEL)
level++; level++;
} }
void IndentedPrint::unindent() void IndentedPrint::unindent()
{ {
if (level > 0) if (level > 0)
level--; level--;
} }
void IndentedPrint::setTabSize(uint8_t n) void IndentedPrint::setTabSize(uint8_t n)
{ {
if (n < MAX_TAB_SIZE) if (n < MAX_TAB_SIZE)
tabSize = n; tabSize = n;
} }
size_t IndentedPrint::write(uint8_t c) size_t IndentedPrint::write(uint8_t c)
{ {
size_t n = 0; size_t n = 0;
if (isNewLine) if (isNewLine)
n += writeTabs(); n += writeTabs();
n += sink.write(c); n += sink.write(c);
isNewLine = c == '\n'; isNewLine = c == '\n';
return n; return n;
} }
inline size_t IndentedPrint::writeTabs() inline size_t IndentedPrint::writeTabs()
{ {
size_t n = 0; size_t n = 0;
for (int i = 0; i < level*tabSize; i++) for (int i = 0; i < level*tabSize; i++)
n += sink.write(' '); n += sink.write(' ');
return n; return n;
} }

View File

@ -1,53 +1,53 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "Print.h" #include "Print.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Generator namespace Generator
{ {
// Decorator on top of Print to allow indented output. // Decorator on top of Print to allow indented output.
// This class is used by JsonPrintable::prettyPrintTo() but can also be used // This class is used by JsonPrintable::prettyPrintTo() but can also be used
// for your own purpose, like logging. // for your own purpose, like logging.
class IndentedPrint : public Print class IndentedPrint : public Print
{ {
public: public:
IndentedPrint(Print& p) IndentedPrint(Print& p)
: sink(p) : sink(p)
{ {
level = 0; level = 0;
tabSize = 2; tabSize = 2;
isNewLine = true; isNewLine = true;
} }
virtual size_t write(uint8_t); virtual size_t write(uint8_t);
// Adds one level of indentation // Adds one level of indentation
void indent(); void indent();
// Removes one level of indentation // Removes one level of indentation
void unindent(); void unindent();
// Set the number of space printed for each level of indentation // Set the number of space printed for each level of indentation
void setTabSize(uint8_t n); void setTabSize(uint8_t n);
private: private:
Print& sink; Print& sink;
uint8_t level : 4; uint8_t level : 4;
uint8_t tabSize : 3; uint8_t tabSize : 3;
bool isNewLine : 1; bool isNewLine : 1;
size_t writeTabs(); size_t writeTabs();
static const int MAX_LEVEL = 15; // because it's only 4 bits static const int MAX_LEVEL = 15; // because it's only 4 bits
static const int MAX_TAB_SIZE = 7; // because it's only 3 bits static const int MAX_TAB_SIZE = 7; // because it's only 3 bits
}; };
} }
} }

View File

@ -1,28 +1,28 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "JsonArrayBase.h" #include "JsonArrayBase.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Generator namespace Generator
{ {
template<int N> template<int N>
class JsonArray : public JsonArrayBase class JsonArray : public JsonArrayBase
{ {
public: public:
JsonArray() JsonArray()
: JsonArrayBase(items, N) : JsonArrayBase(items, N)
{ {
} }
private: private:
JsonValue items[N]; JsonValue items[N];
}; };
} }
} }

View File

@ -1,34 +1,34 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "JsonArrayBase.h" #include "JsonArrayBase.h"
using namespace ArduinoJson::Generator; using namespace ArduinoJson::Generator;
using namespace ArduinoJson::Internals; using namespace ArduinoJson::Internals;
size_t JsonArrayBase::printTo(Print& p) const size_t JsonArrayBase::printTo(Print& p) const
{ {
size_t n = 0; size_t n = 0;
n += p.write('['); n += p.write('[');
// NB: the code has been optimized for a small size on a 8-bit AVR // NB: the code has been optimized for a small size on a 8-bit AVR
const JsonValue* current = items; const JsonValue* current = items;
for (int i = count; i > 0; i--) for (int i = count; i > 0; i--)
{ {
n += current->printTo(p); n += current->printTo(p);
current++; current++;
if (i > 1) if (i > 1)
{ {
n += p.write(','); n += p.write(',');
} }
} }
n += p.write(']'); n += p.write(']');
return n; return n;
} }

View File

@ -1,79 +1,79 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "JsonPrintable.h" #include "JsonPrintable.h"
#include "JsonValue.h" #include "JsonValue.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Generator namespace Generator
{ {
class JsonArrayBase : public JsonPrintable class JsonArrayBase : public JsonPrintable
{ {
public: public:
JsonArrayBase(JsonValue* items, int capacity) JsonArrayBase(JsonValue* items, int capacity)
: items(items), capacity(capacity), count(0) : items(items), capacity(capacity), count(0)
{ {
} }
void add(const Printable& value) void add(const Printable& value)
{ {
addIfPossible<const Printable&>(value); addIfPossible<const Printable&>(value);
} }
void add(bool value) void add(bool value)
{ {
addIfPossible<bool>(value); addIfPossible<bool>(value);
} }
void add(int value) void add(int value)
{ {
addIfPossible<long>(value); addIfPossible<long>(value);
} }
void add(long value) void add(long value)
{ {
addIfPossible<long>(value); addIfPossible<long>(value);
} }
void add(double value) void add(double value)
{ {
addIfPossible<double>(value); addIfPossible<double>(value);
} }
void add(const char* value) void add(const char* value)
{ {
addIfPossible<const char*>(value); addIfPossible<const char*>(value);
} }
template<int DIGITS> template<int DIGITS>
void add(double value) void add(double value)
{ {
if (count >= capacity) return; if (count >= capacity) return;
JsonValue& v = items[count++]; JsonValue& v = items[count++];
v.set<DIGITS>(value); v.set<DIGITS>(value);
} }
virtual size_t printTo(Print& p) const; virtual size_t printTo(Print& p) const;
using JsonPrintable::printTo; using JsonPrintable::printTo;
private: private:
JsonValue* items; JsonValue* items;
int capacity, count; int capacity, count;
template<typename T> template<typename T>
void addIfPossible(T value) void addIfPossible(T value)
{ {
if (count < capacity) if (count < capacity)
items[count++] = value; items[count++] = value;
} }
}; };
} }
} }

View File

@ -1,44 +1,44 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "JsonObjectBase.h" #include "JsonObjectBase.h"
#ifndef ARDUINO_JSON_NO_DEPRECATION_WARNING #ifndef ARDUINO_JSON_NO_DEPRECATION_WARNING
#ifdef __GNUC__ #ifdef __GNUC__
#define DEPRECATED __attribute__((deprecated)) #define DEPRECATED __attribute__((deprecated))
#elif defined(_MSC_VER) #elif defined(_MSC_VER)
#define DEPRECATED __declspec(deprecated) #define DEPRECATED __declspec(deprecated)
#endif #endif
#else #else
#define DEPRECATED #define DEPRECATED
#endif #endif
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Generator namespace Generator
{ {
template <int N> template <int N>
class JsonObject : public JsonObjectBase class JsonObject : public JsonObjectBase
{ {
public: public:
JsonObject() JsonObject()
: JsonObjectBase(items, N) : JsonObjectBase(items, N)
{ {
} }
private: private:
KeyValuePair items[N]; KeyValuePair items[N];
}; };
// Obsolete: use JsonObject instead // Obsolete: use JsonObject instead
template <int N> template <int N>
class DEPRECATED JsonHashTable : public JsonObject<N> class DEPRECATED JsonHashTable : public JsonObject<N>
{ {
}; };
} }
} }

View File

@ -1,92 +1,92 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "JsonObjectBase.h" #include "JsonObjectBase.h"
#include <string.h> // for strcmp #include <string.h> // for strcmp
using namespace ArduinoJson::Generator; using namespace ArduinoJson::Generator;
using namespace ArduinoJson::Internals; using namespace ArduinoJson::Internals;
JsonValue JsonObjectBase::nullValue; JsonValue JsonObjectBase::nullValue;
size_t JsonObjectBase::printTo(Print& p) const size_t JsonObjectBase::printTo(Print& p) const
{ {
size_t n = 0; size_t n = 0;
n += p.write('{'); n += p.write('{');
// NB: the code has been optimized for a small size on a 8-bit AVR // NB: the code has been optimized for a small size on a 8-bit AVR
const KeyValuePair* current = items; const KeyValuePair* current = items;
for (int i = count; i > 0; i--) for (int i = count; i > 0; i--)
{ {
n += EscapedString::printTo(current->key, p); n += EscapedString::printTo(current->key, p);
n += p.write(':'); n += p.write(':');
n += current->value.printTo(p); n += current->value.printTo(p);
current++; current++;
if (i > 1) if (i > 1)
{ {
n += p.write(','); n += p.write(',');
} }
} }
n += p.write('}'); n += p.write('}');
return n; return n;
} }
JsonObjectBase::KeyValuePair* JsonObjectBase::getMatchingPair(JsonKey key) const JsonObjectBase::KeyValuePair* JsonObjectBase::getMatchingPair(JsonKey key) const
{ {
KeyValuePair* p = items; KeyValuePair* p = items;
for (int i = count; i > 0; --i) for (int i = count; i > 0; --i)
{ {
if (!strcmp(p->key, key)) if (!strcmp(p->key, key))
return p; return p;
p++; p++;
} }
return 0; return 0;
} }
JsonValue& JsonObjectBase::operator[](JsonKey key) JsonValue& JsonObjectBase::operator[](JsonKey key)
{ {
KeyValuePair* match = getMatchingPair(key); KeyValuePair* match = getMatchingPair(key);
if (match) if (match)
return match->value; return match->value;
JsonValue* value; JsonValue* value;
if (count < capacity) if (count < capacity)
{ {
items[count].key = key; items[count].key = key;
value = &items[count].value; value = &items[count].value;
count++; count++;
} }
else else
{ {
value = &nullValue; value = &nullValue;
} }
value->reset(); value->reset();
return *value; return *value;
} }
bool JsonObjectBase::containsKey(JsonKey key) const bool JsonObjectBase::containsKey(JsonKey key) const
{ {
return getMatchingPair(key) != 0; return getMatchingPair(key) != 0;
} }
void JsonObjectBase::remove(JsonKey key) void JsonObjectBase::remove(JsonKey key)
{ {
KeyValuePair* match = getMatchingPair(key); KeyValuePair* match = getMatchingPair(key);
if (match == 0) return; if (match == 0) return;
*match = items[--count]; *match = items[--count];
} }

View File

@ -1,62 +1,62 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "JsonPrintable.h" #include "JsonPrintable.h"
#include "JsonValue.h" #include "JsonValue.h"
#include "EscapedString.h" #include "EscapedString.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Generator namespace Generator
{ {
typedef const char* JsonKey; typedef const char* JsonKey;
class JsonObjectBase : public JsonPrintable class JsonObjectBase : public JsonPrintable
{ {
public: public:
JsonValue& operator[](JsonKey); JsonValue& operator[](JsonKey);
bool containsKey(JsonKey) const; bool containsKey(JsonKey) const;
void remove(JsonKey key); void remove(JsonKey key);
template<typename T> template<typename T>
void add(JsonKey key, T value) void add(JsonKey key, T value)
{ {
operator[](key) = value; operator[](key) = value;
} }
template<int DIGITS> template<int DIGITS>
void add(JsonKey key, double value) void add(JsonKey key, double value)
{ {
operator[](key).set<DIGITS>(value); operator[](key).set<DIGITS>(value);
} }
using JsonPrintable::printTo; using JsonPrintable::printTo;
virtual size_t printTo(Print& p) const; virtual size_t printTo(Print& p) const;
protected: protected:
struct KeyValuePair struct KeyValuePair
{ {
JsonKey key; JsonKey key;
JsonValue value; JsonValue value;
}; };
JsonObjectBase(KeyValuePair* items, int capacity) JsonObjectBase(KeyValuePair* items, int capacity)
: items(items), capacity(capacity), count(0) : items(items), capacity(capacity), count(0)
{ {
} }
private: private:
KeyValuePair* items; KeyValuePair* items;
int capacity, count; int capacity, count;
static JsonValue nullValue; static JsonValue nullValue;
KeyValuePair* getMatchingPair(JsonKey key) const; KeyValuePair* getMatchingPair(JsonKey key) const;
}; };
} }
} }

View File

@ -2,96 +2,96 @@
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "JsonPrettyPrint.h" #include "JsonPrettyPrint.h"
using namespace ArduinoJson::Generator; using namespace ArduinoJson::Generator;
size_t JsonPrettyPrint::write(uint8_t c) size_t JsonPrettyPrint::write(uint8_t c)
{ {
size_t n = inString ? handleStringChar(c) : handleMarkupChar(c); size_t n = inString ? handleStringChar(c) : handleMarkupChar(c);
previousChar = c; previousChar = c;
return n; return n;
} }
inline size_t JsonPrettyPrint::handleStringChar(uint8_t c) inline size_t JsonPrettyPrint::handleStringChar(uint8_t c)
{ {
bool isQuote = c == '"' && previousChar != '\\'; bool isQuote = c == '"' && previousChar != '\\';
if (isQuote) inString = false; if (isQuote) inString = false;
return sink.write(c); return sink.write(c);
} }
inline size_t JsonPrettyPrint::handleMarkupChar(uint8_t c) inline size_t JsonPrettyPrint::handleMarkupChar(uint8_t c)
{ {
switch (c) switch (c)
{ {
case '{': case '{':
case '[': case '[':
return handleBlockOpen(c); return handleBlockOpen(c);
case '}': case '}':
case ']': case ']':
return handleBlockClose(c); return handleBlockClose(c);
case ':': case ':':
return handleColumn(); return handleColumn();
case ',': case ',':
return handleComma(); return handleComma();
case '"': case '"':
return handleQuoteOpen(); return handleQuoteOpen();
default: default:
return handleNormalChar(c); return handleNormalChar(c);
} }
} }
inline size_t JsonPrettyPrint::handleBlockOpen(uint8_t c) inline size_t JsonPrettyPrint::handleBlockOpen(uint8_t c)
{ {
return indentIfNeeded() + sink.write(c); return indentIfNeeded() + sink.write(c);
} }
inline size_t JsonPrettyPrint::handleBlockClose(uint8_t c) inline size_t JsonPrettyPrint::handleBlockClose(uint8_t c)
{ {
return unindentIfNeeded() + sink.write(c); return unindentIfNeeded() + sink.write(c);
} }
inline size_t JsonPrettyPrint::handleColumn() inline size_t JsonPrettyPrint::handleColumn()
{ {
return sink.write(':') + sink.write(' '); return sink.write(':') + sink.write(' ');
} }
inline size_t JsonPrettyPrint::handleComma() inline size_t JsonPrettyPrint::handleComma()
{ {
return sink.write(',') + sink.println(); return sink.write(',') + sink.println();
} }
inline size_t JsonPrettyPrint::handleQuoteOpen() inline size_t JsonPrettyPrint::handleQuoteOpen()
{ {
inString = true; inString = true;
return indentIfNeeded() + sink.write('"'); return indentIfNeeded() + sink.write('"');
} }
inline size_t JsonPrettyPrint::handleNormalChar(uint8_t c) inline size_t JsonPrettyPrint::handleNormalChar(uint8_t c)
{ {
return indentIfNeeded() + sink.write(c); return indentIfNeeded() + sink.write(c);
} }
size_t JsonPrettyPrint::indentIfNeeded() size_t JsonPrettyPrint::indentIfNeeded()
{ {
if (!inEmptyBlock()) return 0; if (!inEmptyBlock()) return 0;
sink.indent(); sink.indent();
return sink.println(); return sink.println();
} }
size_t JsonPrettyPrint::unindentIfNeeded() size_t JsonPrettyPrint::unindentIfNeeded()
{ {
if (inEmptyBlock()) return 0; if (inEmptyBlock()) return 0;
sink.unindent(); sink.unindent();
return sink.println(); return sink.println();
} }

View File

@ -1,52 +1,52 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "Print.h" #include "Print.h"
#include "IndentedPrint.h" #include "IndentedPrint.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Generator namespace Generator
{ {
// Converts a compact JSON string into an indented one. // Converts a compact JSON string into an indented one.
class JsonPrettyPrint : public Print class JsonPrettyPrint : public Print
{ {
public: public:
JsonPrettyPrint(IndentedPrint& p) JsonPrettyPrint(IndentedPrint& p)
: sink(p) : sink(p)
{ {
previousChar = 0; previousChar = 0;
inString = false; inString = false;
} }
virtual size_t write(uint8_t); virtual size_t write(uint8_t);
private: private:
uint8_t previousChar; uint8_t previousChar;
IndentedPrint& sink; IndentedPrint& sink;
bool inString; bool inString;
bool inEmptyBlock() bool inEmptyBlock()
{ {
return previousChar == '{' || previousChar == '['; return previousChar == '{' || previousChar == '[';
} }
size_t handleStringChar(uint8_t); size_t handleStringChar(uint8_t);
size_t handleMarkupChar(uint8_t); size_t handleMarkupChar(uint8_t);
size_t handleBlockClose(uint8_t); size_t handleBlockClose(uint8_t);
size_t handleBlockOpen(uint8_t); size_t handleBlockOpen(uint8_t);
size_t handleColumn(); size_t handleColumn();
size_t handleComma(); size_t handleComma();
size_t handleQuoteOpen(); size_t handleQuoteOpen();
size_t handleNormalChar(uint8_t); size_t handleNormalChar(uint8_t);
size_t indentIfNeeded(); size_t indentIfNeeded();
size_t unindentIfNeeded(); size_t unindentIfNeeded();
}; };
} }
} }

View File

@ -1,35 +1,35 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "JsonPrintable.h" #include "JsonPrintable.h"
#include "JsonPrettyPrint.h" #include "JsonPrettyPrint.h"
#include "StringBuilder.h" #include "StringBuilder.h"
using namespace ArduinoJson::Generator; using namespace ArduinoJson::Generator;
using namespace ArduinoJson::Internals; using namespace ArduinoJson::Internals;
size_t JsonPrintable::printTo(char* buffer, size_t bufferSize) const size_t JsonPrintable::printTo(char* buffer, size_t bufferSize) const
{ {
StringBuilder sb(buffer, bufferSize); StringBuilder sb(buffer, bufferSize);
return printTo(sb); return printTo(sb);
} }
size_t JsonPrintable::prettyPrintTo(char* buffer, size_t bufferSize) const size_t JsonPrintable::prettyPrintTo(char* buffer, size_t bufferSize) const
{ {
StringBuilder sb(buffer, bufferSize); StringBuilder sb(buffer, bufferSize);
return prettyPrintTo(sb); return prettyPrintTo(sb);
} }
size_t JsonPrintable::prettyPrintTo(IndentedPrint& p) const size_t JsonPrintable::prettyPrintTo(IndentedPrint& p) const
{ {
JsonPrettyPrint prettyPrint(p); JsonPrettyPrint prettyPrint(p);
return printTo(prettyPrint); return printTo(prettyPrint);
} }
size_t JsonPrintable::prettyPrintTo(Print& p) const size_t JsonPrintable::prettyPrintTo(Print& p) const
{ {
IndentedPrint indentedPrint(p); IndentedPrint indentedPrint(p);
return prettyPrintTo(indentedPrint); return prettyPrintTo(indentedPrint);
} }

View File

@ -1,40 +1,40 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "Print.h" #include "Print.h"
#include "Printable.h" #include "Printable.h"
#include "IndentedPrint.h" #include "IndentedPrint.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Generator namespace Generator
{ {
// Contains methods to generate a JSON string. // Contains methods to generate a JSON string.
// Implemented by both JsonObject and JsonArray // Implemented by both JsonObject and JsonArray
class JsonPrintable : public Printable class JsonPrintable : public Printable
{ {
public: public:
// Generates the compact JSON string and sends it to a Print stream // Generates the compact JSON string and sends it to a Print stream
virtual size_t printTo(Print& p) const = 0; virtual size_t printTo(Print& p) const = 0;
// Generates the compact JSON string and writes it in a buffer // Generates the compact JSON string and writes it in a buffer
size_t printTo(char* buffer, size_t bufferSize) const; size_t printTo(char* buffer, size_t bufferSize) const;
// Generates the indented JSON string and sends it to a Print stream // Generates the indented JSON string and sends it to a Print stream
size_t prettyPrintTo(Print& p) const; size_t prettyPrintTo(Print& p) const;
// Generates the indented JSON string and sends it to a IndentedPrint stream // Generates the indented JSON string and sends it to a IndentedPrint stream
// This overload allows a finer control of the output because you can customize // This overload allows a finer control of the output because you can customize
// the IndentedPrint. // the IndentedPrint.
size_t prettyPrintTo(IndentedPrint& p) const; size_t prettyPrintTo(IndentedPrint& p) const;
// Generates the indented JSON string and writes it in a buffer // Generates the indented JSON string and writes it in a buffer
size_t prettyPrintTo(char* buffer, size_t bufferSize) const; size_t prettyPrintTo(char* buffer, size_t bufferSize) const;
}; };
} }
} }

View File

@ -2,32 +2,32 @@
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "EscapedString.h" #include "EscapedString.h"
#include "JsonValue.h" #include "JsonValue.h"
using namespace ArduinoJson::Generator; using namespace ArduinoJson::Generator;
using namespace ArduinoJson::Internals; using namespace ArduinoJson::Internals;
size_t JsonValue::printBoolTo(const Content& c, Print& p) size_t JsonValue::printBoolTo(const Content& c, Print& p)
{ {
return p.print(c.asBool ? "true" : "false"); return p.print(c.asBool ? "true" : "false");
} }
size_t JsonValue::printLongTo(const Content& c, Print& p) size_t JsonValue::printLongTo(const Content& c, Print& p)
{ {
return p.print(c.asLong); return p.print(c.asLong);
} }
size_t JsonValue::printPrintableTo(const Content& c, Print& p) size_t JsonValue::printPrintableTo(const Content& c, Print& p)
{ {
if (c.asPrintable) if (c.asPrintable)
return c.asPrintable->printTo(p); return c.asPrintable->printTo(p);
else else
return p.print("null"); return p.print("null");
} }
size_t JsonValue::printStringTo(const Content& c, Print& p) size_t JsonValue::printStringTo(const Content& c, Print& p)
{ {
return EscapedString::printTo(c.asString, p); return EscapedString::printTo(c.asString, p);
} }

View File

@ -1,135 +1,135 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "EscapedString.h" #include "EscapedString.h"
#include "Printable.h" #include "Printable.h"
#include "StringBuilder.h" #include "StringBuilder.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Generator namespace Generator
{ {
class JsonValue class JsonValue
{ {
public: public:
void operator=(bool value) void operator=(bool value)
{ {
printToImpl = &printBoolTo; printToImpl = &printBoolTo;
content.asBool = value; content.asBool = value;
} }
void operator=(long value) void operator=(long value)
{ {
printToImpl = &printLongTo; printToImpl = &printLongTo;
content.asLong = value; content.asLong = value;
} }
void operator=(int value) void operator=(int value)
{ {
printToImpl = &printLongTo; printToImpl = &printLongTo;
content.asLong = value; content.asLong = value;
} }
void operator=(const Printable& value) void operator=(const Printable& value)
{ {
printToImpl = &printPrintableTo; printToImpl = &printPrintableTo;
content.asPrintable = &value; content.asPrintable = &value;
} }
void operator=(const char* value) void operator=(const char* value)
{ {
printToImpl = &printStringTo; printToImpl = &printStringTo;
content.asString = value; content.asString = value;
} }
void operator=(double value) void operator=(double value)
{ {
set<2>(value); set<2>(value);
} }
template <int DIGITS> template <int DIGITS>
void set(double value) void set(double value)
{ {
printToImpl = &printDoubleTo < DIGITS > ; printToImpl = &printDoubleTo < DIGITS > ;
content.asDouble = value; content.asDouble = value;
} }
operator bool() operator bool()
{ {
return content.asBool; return content.asBool;
} }
operator const char*() operator const char*()
{ {
return content.asString; return content.asString;
} }
operator double() operator double()
{ {
return content.asDouble; return content.asDouble;
} }
operator float() operator float()
{ {
return (float)content.asDouble; return (float)content.asDouble;
} }
operator int() operator int()
{ {
return content.asLong; return content.asLong;
} }
operator long() operator long()
{ {
return content.asLong; return content.asLong;
} }
operator const Printable&() operator const Printable&()
{ {
return *content.asPrintable; return *content.asPrintable;
} }
size_t printTo(Print& p) const size_t printTo(Print& p) const
{ {
// handmade polymorphism // handmade polymorphism
return printToImpl(content, p); return printToImpl(content, p);
} }
void reset() void reset()
{ {
content.asDouble = 0; content.asDouble = 0;
printToImpl = printStringTo; printToImpl = printStringTo;
} }
private: private:
union Content union Content
{ {
bool asBool; bool asBool;
double asDouble; double asDouble;
long asLong; long asLong;
const Printable* asPrintable; const Printable* asPrintable;
const char* asString; const char* asString;
}; };
Content content; Content content;
size_t(*printToImpl)(const Content&, Print&); size_t(*printToImpl)(const Content&, Print&);
static size_t printBoolTo(const Content&, Print&); static size_t printBoolTo(const Content&, Print&);
static size_t printLongTo(const Content&, Print&); static size_t printLongTo(const Content&, Print&);
static size_t printPrintableTo(const Content&, Print&); static size_t printPrintableTo(const Content&, Print&);
static size_t printStringTo(const Content&, Print&); static size_t printStringTo(const Content&, Print&);
template <int DIGITS> template <int DIGITS>
static size_t printDoubleTo(const Content& c, Print& p) static size_t printDoubleTo(const Content& c, Print& p)
{ {
return p.print(c.asDouble, DIGITS); return p.print(c.asDouble, DIGITS);
} }
}; };
} }
} }

View File

@ -5,52 +5,52 @@
#ifndef ARDUINO #ifndef ARDUINO
#include "Print.h" #include "Print.h"
#include <string> // for sprintf, strchr and strcat #include <string> // for sprintf, strchr and strcat
size_t Print::print(const char s[]) size_t Print::print(const char s[])
{ {
size_t n = 0; size_t n = 0;
while (*s) while (*s)
{ {
n += write(*s++); n += write(*s++);
} }
return n; return n;
} }
static inline void ensureStringContainsPoint(char* s) static inline void ensureStringContainsPoint(char* s)
{ {
// Ensures that the decimal point is present. // Ensures that the decimal point is present.
// For example, we don't want "0" but "0.0". // For example, we don't want "0" but "0.0".
// Otherwise, the value would be considered as an integer by some parsers // Otherwise, the value would be considered as an integer by some parsers
// See issue #22 // See issue #22
if (!strchr(s, '.')) if (!strchr(s, '.'))
strcat(s, ".0"); strcat(s, ".0");
} }
size_t Print::print(double value, int digits) size_t Print::print(double value, int digits)
{ {
char tmp[32]; char tmp[32];
sprintf(tmp, "%.*lg", digits+1, value); sprintf(tmp, "%.*lg", digits+1, value);
if (digits>0) if (digits>0)
ensureStringContainsPoint(tmp); ensureStringContainsPoint(tmp);
return print(tmp); return print(tmp);
} }
size_t Print::print(long value) size_t Print::print(long value)
{ {
char tmp[32]; char tmp[32];
sprintf(tmp, "%ld", value); sprintf(tmp, "%ld", value);
return print(tmp); return print(tmp);
} }
size_t Print::println() size_t Print::println()
{ {
return write('\r') + write('\n'); return write('\r') + write('\n');
} }
#endif #endif

View File

@ -2,29 +2,29 @@
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#ifndef ARDUINO #ifndef ARDUINO
#include <stddef.h> #include <stddef.h>
#include <stdint.h> #include <stdint.h>
// This class reproduces Arduino's Print // This class reproduces Arduino's Print
class Print class Print
{ {
public: public:
virtual size_t write(uint8_t) = 0; virtual size_t write(uint8_t) = 0;
size_t print(const char[]); size_t print(const char[]);
size_t print(double, int = 2); size_t print(double, int = 2);
size_t print(long); size_t print(long);
size_t println(); size_t println();
}; };
#else #else
#include <Print.h> #include <Print.h>
#endif #endif

View File

@ -2,23 +2,23 @@
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#ifndef ARDUINO #ifndef ARDUINO
class Print; class Print;
class Printable class Printable
{ {
public: public:
virtual size_t printTo(Print& p) const = 0; virtual size_t printTo(Print& p) const = 0;
}; };
#else #else
#include <Printable.h> #include <Printable.h>
#endif #endif

View File

@ -1,17 +1,17 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "StringBuilder.h" #include "StringBuilder.h"
using namespace ArduinoJson::Internals; using namespace ArduinoJson::Internals;
size_t StringBuilder::write(uint8_t c) size_t StringBuilder::write(uint8_t c)
{ {
if (length >= capacity) return 0; if (length >= capacity) return 0;
buffer[length++] = c; buffer[length++] = c;
buffer[length] = 0; buffer[length] = 0;
return 1; return 1;
} }

View File

@ -1,31 +1,31 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "Print.h" #include "Print.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Internals namespace Internals
{ {
class StringBuilder : public Print class StringBuilder : public Print
{ {
public: public:
StringBuilder(char* buf, int size) StringBuilder(char* buf, int size)
: buffer(buf), capacity(size - 1), length(0) : buffer(buf), capacity(size - 1), length(0)
{ {
buffer[0] = 0; buffer[0] = 0;
} }
virtual size_t write(uint8_t c); virtual size_t write(uint8_t c);
private: private:
char* buffer; char* buffer;
int capacity; int capacity;
int length; int length;
}; };
} }
} }

View File

@ -1,95 +1,95 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "EscapedString.h" #include "EscapedString.h"
#include "StringBuilder.h" #include "StringBuilder.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace ArduinoJson::Internals; using namespace ArduinoJson::Internals;
namespace JsonGeneratorTests namespace JsonGeneratorTests
{ {
TEST_CLASS(EscapedStringTests) TEST_CLASS(EscapedStringTests)
{ {
char buffer[1024]; char buffer[1024];
size_t returnValue; size_t returnValue;
public: public:
TEST_METHOD(Null) TEST_METHOD(Null)
{ {
whenInputIs(0); whenInputIs(0);
outputMustBe("null"); outputMustBe("null");
} }
TEST_METHOD(EmptyString) TEST_METHOD(EmptyString)
{ {
whenInputIs(""); whenInputIs("");
outputMustBe("\"\""); outputMustBe("\"\"");
} }
TEST_METHOD(QuotationMark) TEST_METHOD(QuotationMark)
{ {
whenInputIs("\""); whenInputIs("\"");
outputMustBe("\"\\\"\""); outputMustBe("\"\\\"\"");
} }
TEST_METHOD(ReverseSolidus) TEST_METHOD(ReverseSolidus)
{ {
whenInputIs("\\"); whenInputIs("\\");
outputMustBe("\"\\\\\""); outputMustBe("\"\\\\\"");
} }
TEST_METHOD(Solidus) TEST_METHOD(Solidus)
{ {
whenInputIs("/"); whenInputIs("/");
outputMustBe("\"/\""); // but the JSON format allows \/ outputMustBe("\"/\""); // but the JSON format allows \/
} }
TEST_METHOD(Backspace) TEST_METHOD(Backspace)
{ {
whenInputIs("\b"); whenInputIs("\b");
outputMustBe("\"\\b\""); outputMustBe("\"\\b\"");
} }
TEST_METHOD(Formfeed) TEST_METHOD(Formfeed)
{ {
whenInputIs("\f"); whenInputIs("\f");
outputMustBe("\"\\f\""); outputMustBe("\"\\f\"");
} }
TEST_METHOD(Newline) TEST_METHOD(Newline)
{ {
whenInputIs("\n"); whenInputIs("\n");
outputMustBe("\"\\n\""); outputMustBe("\"\\n\"");
} }
TEST_METHOD(CarriageReturn) TEST_METHOD(CarriageReturn)
{ {
whenInputIs("\r"); whenInputIs("\r");
outputMustBe("\"\\r\""); outputMustBe("\"\\r\"");
} }
TEST_METHOD(HorizontalTab) TEST_METHOD(HorizontalTab)
{ {
whenInputIs("\t"); whenInputIs("\t");
outputMustBe("\"\\t\""); outputMustBe("\"\\t\"");
} }
private: private:
void whenInputIs(const char* input) void whenInputIs(const char* input)
{ {
StringBuilder sb(buffer, sizeof(buffer)); StringBuilder sb(buffer, sizeof(buffer));
returnValue = EscapedString::printTo(input, sb); returnValue = EscapedString::printTo(input, sb);
} }
void outputMustBe(const char* expected) void outputMustBe(const char* expected)
{ {
Assert::AreEqual(expected, buffer); Assert::AreEqual(expected, buffer);
Assert::AreEqual(strlen(expected), returnValue); Assert::AreEqual(strlen(expected), returnValue);
} }
}; };
} }

View File

@ -1,73 +1,73 @@
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "JsonArray.h" #include "JsonArray.h"
#include "JsonObject.h" #include "JsonObject.h"
using namespace ArduinoJson::Generator; using namespace ArduinoJson::Generator;
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace JsonGeneratorTests namespace JsonGeneratorTests
{ {
TEST_CLASS(Issue10) TEST_CLASS(Issue10)
{ {
struct Person { struct Person {
int id; int id;
char name[32]; char name[32];
}; };
Person persons[2]; Person persons[2];
public: public:
TEST_METHOD_INITIALIZE(Initialize) TEST_METHOD_INITIALIZE(Initialize)
{ {
Person boss; Person boss;
boss.id = 1; boss.id = 1;
strcpy(boss.name, "Jeff"); strcpy(boss.name, "Jeff");
Person employee; Person employee;
employee.id = 2; employee.id = 2;
strcpy(employee.name, "John"); strcpy(employee.name, "John");
persons[0] = boss; persons[0] = boss;
persons[1] = employee; persons[1] = employee;
} }
TEST_METHOD(WrongWayToAddObjectInAnArray) TEST_METHOD(WrongWayToAddObjectInAnArray)
{ {
JsonArray<2> json; JsonArray<2> json;
for (int i = 0; i < 2; i++) for (int i = 0; i < 2; i++)
{ {
JsonObject<2> object; JsonObject<2> object;
object["id"] = persons[i].id; object["id"] = persons[i].id;
object["name"] = persons[i].name; object["name"] = persons[i].name;
json.add(object); // <- Adding a reference to a temporary variable json.add(object); // <- Adding a reference to a temporary variable
} }
char buffer[256]; char buffer[256];
json.printTo(buffer, sizeof(buffer)); json.printTo(buffer, sizeof(buffer));
// the same values are repeated, that's normal // the same values are repeated, that's normal
Assert::AreEqual("[{\"id\":2,\"name\":\"John\"},{\"id\":2,\"name\":\"John\"}]", buffer); Assert::AreEqual("[{\"id\":2,\"name\":\"John\"},{\"id\":2,\"name\":\"John\"}]", buffer);
} }
TEST_METHOD(RightWayToAddObjectInAnArray) TEST_METHOD(RightWayToAddObjectInAnArray)
{ {
JsonArray<2> json; JsonArray<2> json;
JsonObject<2> object[2]; JsonObject<2> object[2];
for (int i = 0; i < 2; i++) for (int i = 0; i < 2; i++)
{ {
object[i]["id"] = persons[i].id; object[i]["id"] = persons[i].id;
object[i]["name"] = persons[i].name; object[i]["name"] = persons[i].name;
json.add(object[i]); json.add(object[i]);
} }
char buffer[256]; char buffer[256];
json.printTo(buffer, sizeof(buffer)); json.printTo(buffer, sizeof(buffer));
Assert::AreEqual("[{\"id\":1,\"name\":\"Jeff\"},{\"id\":2,\"name\":\"John\"}]", buffer); Assert::AreEqual("[{\"id\":1,\"name\":\"Jeff\"},{\"id\":2,\"name\":\"John\"}]", buffer);
} }
}; };
} }

View File

@ -1,162 +1,162 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "JsonArray.h" #include "JsonArray.h"
#include "JsonObject.h" #include "JsonObject.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace ArduinoJson::Generator; using namespace ArduinoJson::Generator;
namespace JsonGeneratorTests namespace JsonGeneratorTests
{ {
TEST_CLASS(JsonArrayTests) TEST_CLASS(JsonArrayTests)
{ {
JsonArray<2> array; JsonArray<2> array;
char buffer[256]; char buffer[256];
public: public:
TEST_METHOD(Empty) TEST_METHOD(Empty)
{ {
outputMustBe("[]"); outputMustBe("[]");
} }
TEST_METHOD(Null) TEST_METHOD(Null)
{ {
array.add((char*) 0); array.add((char*) 0);
outputMustBe("[null]"); outputMustBe("[null]");
} }
TEST_METHOD(OneString) TEST_METHOD(OneString)
{ {
array.add("hello"); array.add("hello");
outputMustBe("[\"hello\"]"); outputMustBe("[\"hello\"]");
} }
TEST_METHOD(TwoStrings) TEST_METHOD(TwoStrings)
{ {
array.add("hello"); array.add("hello");
array.add("world"); array.add("world");
outputMustBe("[\"hello\",\"world\"]"); outputMustBe("[\"hello\",\"world\"]");
} }
TEST_METHOD(OneStringOverCapacity) TEST_METHOD(OneStringOverCapacity)
{ {
array.add("hello"); array.add("hello");
array.add("world"); array.add("world");
array.add("lost"); array.add("lost");
outputMustBe("[\"hello\",\"world\"]"); outputMustBe("[\"hello\",\"world\"]");
} }
TEST_METHOD(OneDoubleDefaultDigits) TEST_METHOD(OneDoubleDefaultDigits)
{ {
array.add(3.14159265358979323846); array.add(3.14159265358979323846);
outputMustBe("[3.14]"); outputMustBe("[3.14]");
} }
TEST_METHOD(OneDoubleFourDigits) TEST_METHOD(OneDoubleFourDigits)
{ {
array.add<4>(3.14159265358979323846); array.add<4>(3.14159265358979323846);
outputMustBe("[3.1416]"); outputMustBe("[3.1416]");
} }
TEST_METHOD(OneInteger) TEST_METHOD(OneInteger)
{ {
array.add(1); array.add(1);
outputMustBe("[1]"); outputMustBe("[1]");
} }
TEST_METHOD(TwoIntegers) TEST_METHOD(TwoIntegers)
{ {
array.add(1); array.add(1);
array.add(2); array.add(2);
outputMustBe("[1,2]"); outputMustBe("[1,2]");
} }
TEST_METHOD(OneIntegerOverCapacity) TEST_METHOD(OneIntegerOverCapacity)
{ {
array.add(1); array.add(1);
array.add(2); array.add(2);
array.add(3); array.add(3);
outputMustBe("[1,2]"); outputMustBe("[1,2]");
} }
TEST_METHOD(OneTrue) TEST_METHOD(OneTrue)
{ {
array.add(true); array.add(true);
outputMustBe("[true]"); outputMustBe("[true]");
} }
TEST_METHOD(OneFalse) TEST_METHOD(OneFalse)
{ {
array.add(false); array.add(false);
outputMustBe("[false]"); outputMustBe("[false]");
} }
TEST_METHOD(TwoBooleans) TEST_METHOD(TwoBooleans)
{ {
array.add(false); array.add(false);
array.add(true); array.add(true);
outputMustBe("[false,true]"); outputMustBe("[false,true]");
} }
TEST_METHOD(OneBooleanOverCapacity) TEST_METHOD(OneBooleanOverCapacity)
{ {
array.add(false); array.add(false);
array.add(true); array.add(true);
array.add(false); array.add(false);
outputMustBe("[false,true]"); outputMustBe("[false,true]");
} }
TEST_METHOD(OneEmptyNestedArray) TEST_METHOD(OneEmptyNestedArray)
{ {
JsonArray<1> nestedArray; JsonArray<1> nestedArray;
array.add(nestedArray); array.add(nestedArray);
outputMustBe("[[]]"); outputMustBe("[[]]");
} }
TEST_METHOD(OneEmptyNestedHash) TEST_METHOD(OneEmptyNestedHash)
{ {
JsonObject<1> nestedObject; JsonObject<1> nestedObject;
array.add(nestedObject); array.add(nestedObject);
outputMustBe("[{}]"); outputMustBe("[{}]");
} }
TEST_METHOD(OneNestedArrayWithOneInteger) TEST_METHOD(OneNestedArrayWithOneInteger)
{ {
JsonArray<1> nestedArray; JsonArray<1> nestedArray;
nestedArray.add(1); nestedArray.add(1);
array.add(nestedArray); array.add(nestedArray);
outputMustBe("[[1]]"); outputMustBe("[[1]]");
} }
private: private:
void outputMustBe(const char* expected) void outputMustBe(const char* expected)
{ {
size_t n = array.printTo(buffer, sizeof(buffer)); size_t n = array.printTo(buffer, sizeof(buffer));
Assert::AreEqual(expected, buffer); Assert::AreEqual(expected, buffer);
Assert::AreEqual(strlen(expected), n); Assert::AreEqual(strlen(expected), n);
} }
}; };
} }

View File

@ -1,73 +1,73 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "JsonArray.h" #include "JsonArray.h"
#include "JsonObject.h" #include "JsonObject.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace ArduinoJson::Generator; using namespace ArduinoJson::Generator;
namespace JsonGeneratorTests namespace JsonGeneratorTests
{ {
TEST_CLASS(JsonObject_Indexer_Tests) TEST_CLASS(JsonObject_Indexer_Tests)
{ {
JsonObject<2> object; JsonObject<2> object;
public: public:
TEST_METHOD(Empty) TEST_METHOD(Empty)
{ {
mustNotContain("key"); mustNotContain("key");
} }
TEST_METHOD(TwoStrings) TEST_METHOD(TwoStrings)
{ {
object["key1"] = "value1"; object["key1"] = "value1";
object["key2"] = "value2"; object["key2"] = "value2";
mustContain("key1", "value1"); mustContain("key1", "value1");
mustContain("key2", "value2"); mustContain("key2", "value2");
} }
TEST_METHOD(RemoveFirst) TEST_METHOD(RemoveFirst)
{ {
object["key1"] = "value1"; object["key1"] = "value1";
object["key2"] = "value2"; object["key2"] = "value2";
object.remove("key1"); object.remove("key1");
mustNotContain("key1"); mustNotContain("key1");
mustContain("key2", "value2"); mustContain("key2", "value2");
} }
TEST_METHOD(RemoveLast) TEST_METHOD(RemoveLast)
{ {
object["key1"] = "value1"; object["key1"] = "value1";
object["key2"] = "value2"; object["key2"] = "value2";
object.remove("key2"); object.remove("key2");
mustContain("key1", "value1"); mustContain("key1", "value1");
mustNotContain("key2"); mustNotContain("key2");
} }
private: private:
void mustContain(const char* key, const char* expected) void mustContain(const char* key, const char* expected)
{ {
Assert::IsTrue(object.containsKey(key)); Assert::IsTrue(object.containsKey(key));
const char* actual = object[key]; const char* actual = object[key];
Assert::AreEqual(expected, actual); Assert::AreEqual(expected, actual);
} }
void mustNotContain(const char* key) void mustNotContain(const char* key)
{ {
Assert::IsFalse(object.containsKey(key)); Assert::IsFalse(object.containsKey(key));
const char* actual = object[key]; const char* actual = object[key];
Assert::IsNull(actual); Assert::IsNull(actual);
} }
}; };
} }

View File

@ -1,152 +1,152 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "JsonArray.h" #include "JsonArray.h"
#include "JsonObject.h" #include "JsonObject.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace ArduinoJson::Generator; using namespace ArduinoJson::Generator;
namespace JsonGeneratorTests namespace JsonGeneratorTests
{ {
TEST_CLASS(JsonObject_PrintTo_Tests) TEST_CLASS(JsonObject_PrintTo_Tests)
{ {
JsonObject<2> object; JsonObject<2> object;
public: public:
TEST_METHOD(Empty) TEST_METHOD(Empty)
{ {
outputMustBe("{}"); outputMustBe("{}");
} }
TEST_METHOD(OneString) TEST_METHOD(OneString)
{ {
object["key"] = "value"; object["key"] = "value";
outputMustBe("{\"key\":\"value\"}"); outputMustBe("{\"key\":\"value\"}");
} }
TEST_METHOD(TwoStrings) TEST_METHOD(TwoStrings)
{ {
object["key1"] = "value1"; object["key1"] = "value1";
object["key2"] = "value2"; object["key2"] = "value2";
outputMustBe("{\"key1\":\"value1\",\"key2\":\"value2\"}"); outputMustBe("{\"key1\":\"value1\",\"key2\":\"value2\"}");
} }
TEST_METHOD(RemoveFirst) TEST_METHOD(RemoveFirst)
{ {
object["key1"] = "value1"; object["key1"] = "value1";
object["key2"] = "value2"; object["key2"] = "value2";
object.remove("key1"); object.remove("key1");
outputMustBe("{\"key2\":\"value2\"}"); outputMustBe("{\"key2\":\"value2\"}");
} }
TEST_METHOD(RemoveLast) TEST_METHOD(RemoveLast)
{ {
object["key1"] = "value1"; object["key1"] = "value1";
object["key2"] = "value2"; object["key2"] = "value2";
object.remove("key2"); object.remove("key2");
outputMustBe("{\"key1\":\"value1\"}"); outputMustBe("{\"key1\":\"value1\"}");
} }
TEST_METHOD(RemoveUnexistingKey) TEST_METHOD(RemoveUnexistingKey)
{ {
object["key1"] = "value1"; object["key1"] = "value1";
object["key2"] = "value2"; object["key2"] = "value2";
object.remove("key3"); object.remove("key3");
outputMustBe("{\"key1\":\"value1\",\"key2\":\"value2\"}"); outputMustBe("{\"key1\":\"value1\",\"key2\":\"value2\"}");
} }
TEST_METHOD(ReplaceExistingKey) TEST_METHOD(ReplaceExistingKey)
{ {
object["key"] = "value1"; object["key"] = "value1";
object["key"] = "value2"; object["key"] = "value2";
outputMustBe("{\"key\":\"value2\"}"); outputMustBe("{\"key\":\"value2\"}");
} }
TEST_METHOD(OneStringOverCapacity) TEST_METHOD(OneStringOverCapacity)
{ {
object["key1"] = "value1"; object["key1"] = "value1";
object["key2"] = "value2"; object["key2"] = "value2";
object["key3"] = "value3"; object["key3"] = "value3";
outputMustBe("{\"key1\":\"value1\",\"key2\":\"value2\"}"); outputMustBe("{\"key1\":\"value1\",\"key2\":\"value2\"}");
} }
TEST_METHOD(OneInteger) TEST_METHOD(OneInteger)
{ {
object["key"] = 1; object["key"] = 1;
outputMustBe("{\"key\":1}"); outputMustBe("{\"key\":1}");
} }
TEST_METHOD(OneDoubleFourDigits) TEST_METHOD(OneDoubleFourDigits)
{ {
object["key"].set<4>(3.14159265358979323846); object["key"].set<4>(3.14159265358979323846);
outputMustBe("{\"key\":3.1416}"); outputMustBe("{\"key\":3.1416}");
} }
TEST_METHOD(OneDoubleDefaultDigits) TEST_METHOD(OneDoubleDefaultDigits)
{ {
object["key"] = 3.14159265358979323846; object["key"] = 3.14159265358979323846;
outputMustBe("{\"key\":3.14}"); outputMustBe("{\"key\":3.14}");
} }
TEST_METHOD(OneNull) TEST_METHOD(OneNull)
{ {
object["key"] = (char*) 0; object["key"] = (char*) 0;
outputMustBe("{\"key\":null}"); outputMustBe("{\"key\":null}");
} }
TEST_METHOD(OneTrue) TEST_METHOD(OneTrue)
{ {
object["key"] = true; object["key"] = true;
outputMustBe("{\"key\":true}"); outputMustBe("{\"key\":true}");
} }
TEST_METHOD(OneFalse) TEST_METHOD(OneFalse)
{ {
object["key"] = false; object["key"] = false;
outputMustBe("{\"key\":false}"); outputMustBe("{\"key\":false}");
} }
TEST_METHOD(OneEmptyNestedArray) TEST_METHOD(OneEmptyNestedArray)
{ {
auto nestedArray = JsonArray<1>(); auto nestedArray = JsonArray<1>();
object["key"] = nestedArray; object["key"] = nestedArray;
outputMustBe("{\"key\":[]}"); outputMustBe("{\"key\":[]}");
} }
TEST_METHOD(OneEmptyNestedObject) TEST_METHOD(OneEmptyNestedObject)
{ {
auto nestedObject = JsonObject<1>(); auto nestedObject = JsonObject<1>();
object["key"] = nestedObject; object["key"] = nestedObject;
outputMustBe("{\"key\":{}}"); outputMustBe("{\"key\":{}}");
} }
private: private:
void outputMustBe(const char* expected) void outputMustBe(const char* expected)
{ {
char buffer[256]; char buffer[256];
size_t result; size_t result;
result = object.printTo(buffer, sizeof(buffer)); result = object.printTo(buffer, sizeof(buffer));
Assert::AreEqual(strlen(expected), result); Assert::AreEqual(strlen(expected), result);
Assert::AreEqual(expected, buffer); Assert::AreEqual(expected, buffer);
} }
}; };
} }

View File

@ -1,78 +1,78 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "StringBuilder.h" #include "StringBuilder.h"
#include "JsonValue.h" #include "JsonValue.h"
#include "JsonArray.h" #include "JsonArray.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace ArduinoJson::Generator; using namespace ArduinoJson::Generator;
using namespace ArduinoJson::Internals; using namespace ArduinoJson::Internals;
namespace JsonGeneratorTests namespace JsonGeneratorTests
{ {
TEST_CLASS(JsonValue_Cast_Tests) TEST_CLASS(JsonValue_Cast_Tests)
{ {
JsonValue value; JsonValue value;
public: public:
TEST_METHOD(Bool) TEST_METHOD(Bool)
{ {
setValueAndCheckCast(true); setValueAndCheckCast(true);
setValueAndCheckCast(false); setValueAndCheckCast(false);
} }
TEST_METHOD(Double) TEST_METHOD(Double)
{ {
setValueAndCheckCast(3.14156); setValueAndCheckCast(3.14156);
} }
TEST_METHOD(Float) TEST_METHOD(Float)
{ {
setValueAndCheckCast(3.14f); setValueAndCheckCast(3.14f);
} }
TEST_METHOD(Integer) TEST_METHOD(Integer)
{ {
setValueAndCheckCast(42); setValueAndCheckCast(42);
} }
TEST_METHOD(Long) TEST_METHOD(Long)
{ {
setValueAndCheckCast(42L); setValueAndCheckCast(42L);
} }
TEST_METHOD(Array) TEST_METHOD(Array)
{ {
JsonArray<2> array; JsonArray<2> array;
setValueAndCheckCast(array); setValueAndCheckCast(array);
} }
TEST_METHOD(String) TEST_METHOD(String)
{ {
setValueAndCheckCast("hello"); setValueAndCheckCast("hello");
} }
private: private:
template<typename T> template<typename T>
void setValueAndCheckCast(T expected) void setValueAndCheckCast(T expected)
{ {
value = expected; value = expected;
T actual = value; T actual = value;
Assert::AreEqual(expected, actual); Assert::AreEqual(expected, actual);
} }
template<int N> template<int N>
void setValueAndCheckCast(JsonArray<N>& expected) void setValueAndCheckCast(JsonArray<N>& expected)
{ {
value = expected; value = expected;
const Printable& actual = value; const Printable& actual = value;
Assert::AreEqual((void*) &expected, (void*) &actual); Assert::AreEqual((void*) &expected, (void*) &actual);
} }
}; };
} }

View File

@ -1,109 +1,109 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "StringBuilder.h" #include "StringBuilder.h"
#include "JsonValue.h" #include "JsonValue.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace ArduinoJson::Generator; using namespace ArduinoJson::Generator;
using namespace ArduinoJson::Internals; using namespace ArduinoJson::Internals;
namespace JsonGeneratorTests namespace JsonGeneratorTests
{ {
TEST_CLASS(JsonValue_PrintTo_Tests) TEST_CLASS(JsonValue_PrintTo_Tests)
{ {
char buffer[1024]; char buffer[1024];
size_t returnValue; size_t returnValue;
public: public:
TEST_METHOD(String) TEST_METHOD(String)
{ {
setValueTo("hello"); setValueTo("hello");
outputMustBe("\"hello\""); outputMustBe("\"hello\"");
} }
TEST_METHOD(ZeroFloat) TEST_METHOD(ZeroFloat)
{ {
setValueTo(0.0f); setValueTo(0.0f);
outputMustBe("0.0"); outputMustBe("0.0");
} }
TEST_METHOD(Float) TEST_METHOD(Float)
{ {
setValueTo(3.1415f); setValueTo(3.1415f);
outputMustBe("3.14"); outputMustBe("3.14");
} }
TEST_METHOD(DoubleZeroDigits) TEST_METHOD(DoubleZeroDigits)
{ {
setValueTo<0>(3.14159265358979323846); setValueTo<0>(3.14159265358979323846);
outputMustBe("3"); outputMustBe("3");
} }
TEST_METHOD(DoubleOneDigit) TEST_METHOD(DoubleOneDigit)
{ {
setValueTo<1>(3.14159265358979323846); setValueTo<1>(3.14159265358979323846);
outputMustBe("3.1"); outputMustBe("3.1");
} }
TEST_METHOD(DoubleTwoDigits) TEST_METHOD(DoubleTwoDigits)
{ {
setValueTo<2>(3.14159265358979323846); setValueTo<2>(3.14159265358979323846);
outputMustBe("3.14"); outputMustBe("3.14");
} }
TEST_METHOD(Integer) TEST_METHOD(Integer)
{ {
setValueTo(314); setValueTo(314);
outputMustBe("314"); outputMustBe("314");
} }
TEST_METHOD(Char) TEST_METHOD(Char)
{ {
setValueTo('A'); setValueTo('A');
outputMustBe("65"); outputMustBe("65");
} }
TEST_METHOD(Short) TEST_METHOD(Short)
{ {
setValueTo((short)314); setValueTo((short)314);
outputMustBe("314"); outputMustBe("314");
} }
TEST_METHOD(Long) TEST_METHOD(Long)
{ {
setValueTo(314159265L); setValueTo(314159265L);
outputMustBe("314159265"); outputMustBe("314159265");
} }
private: private:
template<int DIGITS> template<int DIGITS>
void setValueTo(double value) void setValueTo(double value)
{ {
StringBuilder sb(buffer, sizeof(buffer)); StringBuilder sb(buffer, sizeof(buffer));
JsonValue jsonValue; JsonValue jsonValue;
jsonValue.set<DIGITS>(value); jsonValue.set<DIGITS>(value);
returnValue = jsonValue.printTo(sb); returnValue = jsonValue.printTo(sb);
} }
template<typename T> template<typename T>
void setValueTo(T value) void setValueTo(T value)
{ {
StringBuilder sb(buffer, sizeof(buffer)); StringBuilder sb(buffer, sizeof(buffer));
JsonValue jsonValue; JsonValue jsonValue;
jsonValue = value; jsonValue = value;
returnValue = jsonValue.printTo(sb); returnValue = jsonValue.printTo(sb);
} }
void outputMustBe(const char* expected) void outputMustBe(const char* expected)
{ {
Assert::AreEqual(expected, buffer); Assert::AreEqual(expected, buffer);
Assert::AreEqual(strlen(expected), returnValue); Assert::AreEqual(strlen(expected), returnValue);
} }
}; };
} }

View File

@ -1,91 +1,91 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "JsonPrettyPrint.h" #include "JsonPrettyPrint.h"
#include "StringBuilder.h" #include "StringBuilder.h"
using namespace ArduinoJson::Internals; using namespace ArduinoJson::Internals;
using namespace ArduinoJson::Generator; using namespace ArduinoJson::Generator;
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace JsonGeneratorTests namespace JsonGeneratorTests
{ {
TEST_CLASS(PrettyPrint_Array_Tests) TEST_CLASS(PrettyPrint_Array_Tests)
{ {
char buffer[1024]; char buffer[1024];
size_t returnValue; size_t returnValue;
public: public:
TEST_METHOD(EmptyArray) TEST_METHOD(EmptyArray)
{ {
whenInputIs("[]"); whenInputIs("[]");
outputMustBe("[]"); outputMustBe("[]");
} }
TEST_METHOD(OneElement) TEST_METHOD(OneElement)
{ {
whenInputIs("[1]"); whenInputIs("[1]");
outputMustBe( outputMustBe(
"[\r\n" "[\r\n"
" 1\r\n" " 1\r\n"
"]"); "]");
} }
TEST_METHOD(TwoElements) TEST_METHOD(TwoElements)
{ {
whenInputIs("[1,2]"); whenInputIs("[1,2]");
outputMustBe( outputMustBe(
"[\r\n" "[\r\n"
" 1,\r\n" " 1,\r\n"
" 2\r\n" " 2\r\n"
"]"); "]");
} }
TEST_METHOD(EmptyNestedArrays) TEST_METHOD(EmptyNestedArrays)
{ {
whenInputIs("[[],[]]"); whenInputIs("[[],[]]");
outputMustBe( outputMustBe(
"[\r\n" "[\r\n"
" [],\r\n" " [],\r\n"
" []\r\n" " []\r\n"
"]"); "]");
} }
TEST_METHOD(NestedArrays) TEST_METHOD(NestedArrays)
{ {
whenInputIs("[[1,2],[3,4]]"); whenInputIs("[[1,2],[3,4]]");
outputMustBe( outputMustBe(
"[\r\n" "[\r\n"
" [\r\n" " [\r\n"
" 1,\r\n" " 1,\r\n"
" 2\r\n" " 2\r\n"
" ],\r\n" " ],\r\n"
" [\r\n" " [\r\n"
" 3,\r\n" " 3,\r\n"
" 4\r\n" " 4\r\n"
" ]\r\n" " ]\r\n"
"]"); "]");
} }
private: private:
void whenInputIs(const char input[]) void whenInputIs(const char input[])
{ {
StringBuilder sb(buffer, sizeof(buffer)); StringBuilder sb(buffer, sizeof(buffer));
IndentedPrint indentedPrint(sb); IndentedPrint indentedPrint(sb);
JsonPrettyPrint decorator(indentedPrint); JsonPrettyPrint decorator(indentedPrint);
returnValue = decorator.print(input); returnValue = decorator.print(input);
} }
void outputMustBe(const char* expected) void outputMustBe(const char* expected)
{ {
Assert::AreEqual(expected, buffer); Assert::AreEqual(expected, buffer);
Assert::AreEqual(strlen(expected), returnValue); Assert::AreEqual(strlen(expected), returnValue);
} }
}; };
} }

View File

@ -1,89 +1,89 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "JsonPrettyPrint.h" #include "JsonPrettyPrint.h"
#include "StringBuilder.h" #include "StringBuilder.h"
using namespace ArduinoJson::Internals; using namespace ArduinoJson::Internals;
using namespace ArduinoJson::Generator; using namespace ArduinoJson::Generator;
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace JsonGeneratorTests namespace JsonGeneratorTests
{ {
TEST_CLASS(PrettyPrint_Object_Tests) TEST_CLASS(PrettyPrint_Object_Tests)
{ {
char buffer[1024]; char buffer[1024];
size_t returnValue; size_t returnValue;
public: public:
TEST_METHOD(EmptyObject) TEST_METHOD(EmptyObject)
{ {
whenInputIs("{}"); whenInputIs("{}");
outputMustBe("{}"); outputMustBe("{}");
} }
TEST_METHOD(OneMember) TEST_METHOD(OneMember)
{ {
whenInputIs("{\"key\":\"value\"}"); whenInputIs("{\"key\":\"value\"}");
outputMustBe( outputMustBe(
"{\r\n" "{\r\n"
" \"key\": \"value\"\r\n" " \"key\": \"value\"\r\n"
"}"); "}");
} }
TEST_METHOD(TwoMembers) TEST_METHOD(TwoMembers)
{ {
whenInputIs("{\"key1\":\"value1\",\"key2\":\"value2\"}"); whenInputIs("{\"key1\":\"value1\",\"key2\":\"value2\"}");
outputMustBe( outputMustBe(
"{\r\n" "{\r\n"
" \"key1\": \"value1\",\r\n" " \"key1\": \"value1\",\r\n"
" \"key2\": \"value2\"\r\n" " \"key2\": \"value2\"\r\n"
"}"); "}");
} }
TEST_METHOD(EmptyNestedObjects) TEST_METHOD(EmptyNestedObjects)
{ {
whenInputIs("{\"key1\":{},\"key2\":{}}"); whenInputIs("{\"key1\":{},\"key2\":{}}");
outputMustBe( outputMustBe(
"{\r\n" "{\r\n"
" \"key1\": {},\r\n" " \"key1\": {},\r\n"
" \"key2\": {}\r\n" " \"key2\": {}\r\n"
"}"); "}");
} }
TEST_METHOD(NestedObjects) TEST_METHOD(NestedObjects)
{ {
whenInputIs("{\"key1\":{\"a\":1},\"key2\":{\"b\":2}}"); whenInputIs("{\"key1\":{\"a\":1},\"key2\":{\"b\":2}}");
outputMustBe( outputMustBe(
"{\r\n" "{\r\n"
" \"key1\": {\r\n" " \"key1\": {\r\n"
" \"a\": 1\r\n" " \"a\": 1\r\n"
" },\r\n" " },\r\n"
" \"key2\": {\r\n" " \"key2\": {\r\n"
" \"b\": 2\r\n" " \"b\": 2\r\n"
" }\r\n" " }\r\n"
"}"); "}");
} }
private: private:
void whenInputIs(const char input[]) void whenInputIs(const char input[])
{ {
StringBuilder sb(buffer, sizeof(buffer)); StringBuilder sb(buffer, sizeof(buffer));
IndentedPrint indentedPrint(sb); IndentedPrint indentedPrint(sb);
JsonPrettyPrint decorator(indentedPrint); JsonPrettyPrint decorator(indentedPrint);
returnValue = decorator.print(input); returnValue = decorator.print(input);
} }
void outputMustBe(const char* expected) void outputMustBe(const char* expected)
{ {
Assert::AreEqual(expected, buffer); Assert::AreEqual(expected, buffer);
Assert::AreEqual(strlen(expected), returnValue); Assert::AreEqual(strlen(expected), returnValue);
} }
}; };
} }

View File

@ -1,76 +1,76 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "JsonPrettyPrint.h" #include "JsonPrettyPrint.h"
#include "StringBuilder.h" #include "StringBuilder.h"
using namespace ArduinoJson::Internals; using namespace ArduinoJson::Internals;
using namespace ArduinoJson::Generator; using namespace ArduinoJson::Generator;
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace JsonGeneratorTests namespace JsonGeneratorTests
{ {
TEST_CLASS(PrettyPrint_String_Tests) TEST_CLASS(PrettyPrint_String_Tests)
{ {
char buffer[1024]; char buffer[1024];
size_t returnValue; size_t returnValue;
public: public:
TEST_METHOD(EmptyString) TEST_METHOD(EmptyString)
{ {
whenInputIs(""); whenInputIs("");
outputMustBe(""); outputMustBe("");
} }
TEST_METHOD(TrickyCharacters) TEST_METHOD(TrickyCharacters)
{ {
whenInputIs ("\":\\\"',\""); whenInputIs ("\":\\\"',\"");
outputMustBe("\":\\\"',\""); outputMustBe("\":\\\"',\"");
} }
TEST_METHOD(OpeningCurlyBrace) TEST_METHOD(OpeningCurlyBrace)
{ {
whenInputIs ("\"{\""); whenInputIs ("\"{\"");
outputMustBe("\"{\""); outputMustBe("\"{\"");
} }
TEST_METHOD(OpeningSquareBrace) TEST_METHOD(OpeningSquareBrace)
{ {
whenInputIs("\"[\""); whenInputIs("\"[\"");
outputMustBe("\"[\""); outputMustBe("\"[\"");
} }
TEST_METHOD(ClosingCurlyBrace) TEST_METHOD(ClosingCurlyBrace)
{ {
whenInputIs("\"}\""); whenInputIs("\"}\"");
outputMustBe("\"}\""); outputMustBe("\"}\"");
} }
TEST_METHOD(ClosingSquareBrace) TEST_METHOD(ClosingSquareBrace)
{ {
whenInputIs("\"]\""); whenInputIs("\"]\"");
outputMustBe("\"]\""); outputMustBe("\"]\"");
} }
private: private:
void whenInputIs(const char input[]) void whenInputIs(const char input[])
{ {
StringBuilder sb(buffer, sizeof(buffer)); StringBuilder sb(buffer, sizeof(buffer));
IndentedPrint indentedPrint(sb); IndentedPrint indentedPrint(sb);
JsonPrettyPrint decorator(indentedPrint); JsonPrettyPrint decorator(indentedPrint);
returnValue = decorator.print(input); returnValue = decorator.print(input);
} }
void outputMustBe(const char* expected) void outputMustBe(const char* expected)
{ {
Assert::AreEqual(expected, buffer); Assert::AreEqual(expected, buffer);
Assert::AreEqual(strlen(expected), returnValue); Assert::AreEqual(strlen(expected), returnValue);
} }
}; };
} }

View File

@ -1,85 +1,85 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "StringBuilder.h" #include "StringBuilder.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace ArduinoJson::Internals; using namespace ArduinoJson::Internals;
namespace JsonGeneratorTests namespace JsonGeneratorTests
{ {
TEST_CLASS(StringBuilderTests) TEST_CLASS(StringBuilderTests)
{ {
char buffer[20]; char buffer[20];
Print* sb; Print* sb;
size_t returnValue; size_t returnValue;
public: public:
TEST_METHOD_INITIALIZE(Initialize) TEST_METHOD_INITIALIZE(Initialize)
{ {
sb = new StringBuilder(buffer, sizeof(buffer)); sb = new StringBuilder(buffer, sizeof(buffer));
} }
TEST_METHOD(InitialState) TEST_METHOD(InitialState)
{ {
outputMustBe(""); outputMustBe("");
} }
TEST_METHOD(OverCapacity) TEST_METHOD(OverCapacity)
{ {
print("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); print("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
resultMustBe(19); resultMustBe(19);
print("ABC"); print("ABC");
resultMustBe(0); resultMustBe(0);
outputMustBe("ABCDEFGHIJKLMNOPQRS"); outputMustBe("ABCDEFGHIJKLMNOPQRS");
} }
TEST_METHOD(EmptyString) TEST_METHOD(EmptyString)
{ {
print(""); print("");
resultMustBe(0); resultMustBe(0);
outputMustBe(""); outputMustBe("");
} }
TEST_METHOD(OneString) TEST_METHOD(OneString)
{ {
print("ABCD"); print("ABCD");
resultMustBe(4); resultMustBe(4);
outputMustBe("ABCD"); outputMustBe("ABCD");
} }
TEST_METHOD(TwoStrings) TEST_METHOD(TwoStrings)
{ {
print("ABCD"); print("ABCD");
resultMustBe(4); resultMustBe(4);
print("EFGH"); print("EFGH");
resultMustBe(4); resultMustBe(4);
outputMustBe("ABCDEFGH"); outputMustBe("ABCDEFGH");
} }
private: private:
void print(const char* value) void print(const char* value)
{ {
returnValue = sb->print(value); returnValue = sb->print(value);
} }
void outputMustBe(const char* expected) void outputMustBe(const char* expected)
{ {
Assert::AreEqual(expected, buffer); Assert::AreEqual(expected, buffer);
} }
void resultMustBe(size_t expected) void resultMustBe(size_t expected)
{ {
Assert::AreEqual(expected, returnValue); Assert::AreEqual(expected, returnValue);
} }
}; };
} }

View File

@ -1,13 +1,13 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
// This file is here to help the Arduino IDE find the .cpp files // This file is here to help the Arduino IDE find the .cpp files
#include "JsonParser/JsonArray.cpp" #include "JsonParser/JsonArray.cpp"
#include "JsonParser/JsonObject.cpp" #include "JsonParser/JsonObject.cpp"
#include "JsonParser/JsonParserBase.cpp" #include "JsonParser/JsonParserBase.cpp"
#include "JsonParser/JsonValue.cpp" #include "JsonParser/JsonValue.cpp"
#include "JsonParser/JsonToken.cpp" #include "JsonParser/JsonToken.cpp"
#include "JsonParser/jsmn.cpp" #include "JsonParser/jsmn.cpp"

View File

@ -1,6 +1,6 @@
/* /*
* malloc-free JSON parser for Arduino * malloc-free JSON parser for Arduino
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "JsonParser/JsonParser.h" #include "JsonParser/JsonParser.h"

View File

@ -2,13 +2,13 @@
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "JsonArray.h" #include "JsonArray.h"
#include "JsonObject.h" #include "JsonObject.h"
using namespace ArduinoJson::Parser; using namespace ArduinoJson::Parser;
DEPRECATED JsonObject JsonArray::getHashTable(int index) DEPRECATED JsonObject JsonArray::getHashTable(int index)
{ {
return operator[](index); return operator[](index);
} }

View File

@ -2,102 +2,102 @@
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "JsonValue.h" #include "JsonValue.h"
#include "JsonArrayIterator.h" #include "JsonArrayIterator.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Parser namespace Parser
{ {
class JsonObject; class JsonObject;
// A JSON array // A JSON array
class JsonArray : JsonValue class JsonArray : JsonValue
{ {
public: public:
// Create an invalid array // Create an invalid array
JsonArray() JsonArray()
{ {
} }
// Convert a JsonValue into a JsonArray // Convert a JsonValue into a JsonArray
JsonArray(JsonValue value) JsonArray(JsonValue value)
: JsonValue(value) : JsonValue(value)
{ {
} }
// Tell if the array is valid // Tell if the array is valid
bool success() bool success()
{ {
return isArray(); return isArray();
} }
// Get the JsonValue at specified index // Get the JsonValue at specified index
JsonValue operator[](int index) JsonValue operator[](int index)
{ {
return JsonValue::operator[](index); return JsonValue::operator[](index);
} }
// Get the size of the array // Get the size of the array
int size() int size()
{ {
return isArray() ? childrenCount() : 0; return isArray() ? childrenCount() : 0;
} }
// Get an iterator pointing to the beginning of the array // Get an iterator pointing to the beginning of the array
JsonArrayIterator begin() JsonArrayIterator begin()
{ {
return isArray() ? firstChild() : null(); return isArray() ? firstChild() : null();
} }
// Gets an iterator pointing to the end of the array // Gets an iterator pointing to the end of the array
JsonArrayIterator end() JsonArrayIterator end()
{ {
return isArray() ? nextSibling() : null(); return isArray() ? nextSibling() : null();
} }
// Obsolete: Use size() instead // Obsolete: Use size() instead
DEPRECATED int getLength() DEPRECATED int getLength()
{ {
return size(); return size();
} }
// Obsolete: Use operator[] instead // Obsolete: Use operator[] instead
DEPRECATED JsonArray getArray(int index) DEPRECATED JsonArray getArray(int index)
{ {
return operator[](index); return operator[](index);
} }
// Obsolete: Use operator[] instead // Obsolete: Use operator[] instead
DEPRECATED bool getBool(int index) DEPRECATED bool getBool(int index)
{ {
return operator[](index); return operator[](index);
} }
// Obsolete: Use operator[] instead // Obsolete: Use operator[] instead
DEPRECATED double getDouble(int index) DEPRECATED double getDouble(int index)
{ {
return operator[](index); return operator[](index);
} }
// Obsolete: Use operator[] instead // Obsolete: Use operator[] instead
DEPRECATED JsonObject getHashTable(int index); DEPRECATED JsonObject getHashTable(int index);
// Obsolete: Use operator[] instead // Obsolete: Use operator[] instead
DEPRECATED long getLong(int index) DEPRECATED long getLong(int index)
{ {
return operator[](index); return operator[](index);
} }
// Obsolete: Use operator[] instead // Obsolete: Use operator[] instead
DEPRECATED char* getString(int index) DEPRECATED char* getString(int index)
{ {
return operator[](index); return operator[](index);
} }
}; };
} }
} }

View File

@ -2,45 +2,45 @@
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "JsonValue.h" #include "JsonValue.h"
#include "JsonToken.h" #include "JsonToken.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Parser namespace Parser
{ {
// An iterator for JsonArray // An iterator for JsonArray
class JsonArrayIterator : JsonToken class JsonArrayIterator : JsonToken
{ {
public: public:
// Create an iterator pointing at the specified JsonToken // Create an iterator pointing at the specified JsonToken
JsonArrayIterator(JsonToken token) JsonArrayIterator(JsonToken token)
: JsonToken(token) : JsonToken(token)
{ {
} }
// Move iterator forward // Move iterator forward
void operator++() void operator++()
{ {
*this = JsonArrayIterator(nextSibling()); *this = JsonArrayIterator(nextSibling());
} }
// Get the value pointed by the iterator // Get the value pointed by the iterator
JsonValue operator*() const JsonValue operator*() const
{ {
return JsonValue(*this); return JsonValue(*this);
} }
// Test iterator equality // Test iterator equality
bool operator!= (const JsonArrayIterator& other) const bool operator!= (const JsonArrayIterator& other) const
{ {
return JsonToken::operator!=(other); return JsonToken::operator!=(other);
} }
}; };
} }
} }

View File

@ -1,15 +1,15 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "JsonArray.h" #include "JsonArray.h"
#include "JsonObject.h" #include "JsonObject.h"
#include "JsonValue.h" #include "JsonValue.h"
using namespace ArduinoJson::Parser; using namespace ArduinoJson::Parser;
DEPRECATED JsonArray JsonObject::getArray(const char* key) DEPRECATED JsonArray JsonObject::getArray(const char* key)
{ {
return operator[](key); return operator[](key);
} }

View File

@ -2,101 +2,101 @@
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "JsonValue.h" #include "JsonValue.h"
#include "JsonObjectIterator.h" #include "JsonObjectIterator.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Parser namespace Parser
{ {
class JsonArray; class JsonArray;
// A JSON Object (ie hash-table/dictionary) // A JSON Object (ie hash-table/dictionary)
class JsonObject : JsonValue class JsonObject : JsonValue
{ {
public: public:
// Create an invalid JsonObject // Create an invalid JsonObject
JsonObject() JsonObject()
{ {
} }
// Convert a JsonValue into a JsonObject // Convert a JsonValue into a JsonObject
JsonObject(JsonValue value) JsonObject(JsonValue value)
: JsonValue(value) : JsonValue(value)
{ {
} }
// Tell if the object is valid // Tell if the object is valid
bool success() bool success()
{ {
return isObject(); return isObject();
} }
// Get the value associated with the specified key. // Get the value associated with the specified key.
JsonValue operator[](const char* key) JsonValue operator[](const char* key)
{ {
return JsonValue::operator[](key); return JsonValue::operator[](key);
} }
// Tell if the specified key exists in the object. // Tell if the specified key exists in the object.
bool containsKey(const char* key) bool containsKey(const char* key)
{ {
return operator[](key).success(); return operator[](key).success();
} }
// Get an iterator pointing at the beginning of the object // Get an iterator pointing at the beginning of the object
JsonObjectIterator begin() JsonObjectIterator begin()
{ {
return isObject() ? firstChild() : null(); return isObject() ? firstChild() : null();
} }
// Get an iterator pointing at the end of the object // Get an iterator pointing at the end of the object
JsonObjectIterator end() JsonObjectIterator end()
{ {
return isObject() ? nextSibling() : null(); return isObject() ? nextSibling() : null();
} }
// Obsolete: Use operator[] instead // Obsolete: Use operator[] instead
DEPRECATED JsonArray getArray(const char* key); DEPRECATED JsonArray getArray(const char* key);
// Obsolete: Use operator[] instead // Obsolete: Use operator[] instead
DEPRECATED bool getBool(const char* key) DEPRECATED bool getBool(const char* key)
{ {
return operator[](key); return operator[](key);
} }
// Obsolete: Use operator[] instead // Obsolete: Use operator[] instead
DEPRECATED double getDouble(const char* key) DEPRECATED double getDouble(const char* key)
{ {
return operator[](key); return operator[](key);
} }
// Obsolete: Use operator[] instead // Obsolete: Use operator[] instead
DEPRECATED JsonObject getHashTable(const char* key) DEPRECATED JsonObject getHashTable(const char* key)
{ {
return operator[](key); return operator[](key);
} }
// Obsolete: Use operator[] instead // Obsolete: Use operator[] instead
DEPRECATED long getLong(const char* key) DEPRECATED long getLong(const char* key)
{ {
return operator[](key); return operator[](key);
} }
// Obsolete: Use operator[] instead // Obsolete: Use operator[] instead
DEPRECATED char* getString(const char* key) DEPRECATED char* getString(const char* key)
{ {
return operator[](key); return operator[](key);
} }
}; };
// Obsolete: Use JsonObject instead // Obsolete: Use JsonObject instead
DEPRECATED typedef JsonObject JsonHashTable; DEPRECATED typedef JsonObject JsonHashTable;
} }
} }

View File

@ -2,57 +2,57 @@
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "JsonValue.h" #include "JsonValue.h"
#include "JsonPair.h" #include "JsonPair.h"
#include "JsonToken.h" #include "JsonToken.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Parser namespace Parser
{ {
// An iterator for JsonObject // An iterator for JsonObject
class JsonObjectIterator : JsonToken class JsonObjectIterator : JsonToken
{ {
public: public:
// Create an iterator pointing at the specified token // Create an iterator pointing at the specified token
JsonObjectIterator(JsonToken token) JsonObjectIterator(JsonToken token)
: JsonToken(token) : JsonToken(token)
{ {
} }
// Move to the next JsonPair // Move to the next JsonPair
void operator++() void operator++()
{ {
*this = JsonObjectIterator(nextSibling().nextSibling()); *this = JsonObjectIterator(nextSibling().nextSibling());
} }
// Get the JsonPair pointed by the iterator // Get the JsonPair pointed by the iterator
JsonPair operator*() const JsonPair operator*() const
{ {
return JsonPair(*this); return JsonPair(*this);
} }
// Test iterator equality // Test iterator equality
bool operator!= (const JsonObjectIterator& other) const bool operator!= (const JsonObjectIterator& other) const
{ {
return JsonToken::operator!=(other); return JsonToken::operator!=(other);
} }
// Get the key of the JsonPair pointed by the iterator // Get the key of the JsonPair pointed by the iterator
const char* key() const const char* key() const
{ {
return operator*().key(); return operator*().key();
} }
// Get the key of the JsonPair pointed by the iterator // Get the key of the JsonPair pointed by the iterator
JsonValue value() const JsonValue value() const
{ {
return operator*().value(); return operator*().value();
} }
}; };
} }
} }

View File

@ -1,37 +1,37 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "JsonValue.h" #include "JsonValue.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Parser namespace Parser
{ {
// A JSON key-value pair, as a part of a JSON object // A JSON key-value pair, as a part of a JSON object
class JsonPair : JsonToken class JsonPair : JsonToken
{ {
public: public:
// Convert a JsonToken to a JsonPair // Convert a JsonToken to a JsonPair
JsonPair(JsonToken token) JsonPair(JsonToken token)
: JsonToken(token) : JsonToken(token)
{ {
} }
// Get the key // Get the key
const char* key() const char* key()
{ {
return getText(); return getText();
} }
// Get the value // Get the value
JsonValue value() JsonValue value()
{ {
return nextSibling(); return nextSibling();
} }
}; };
} }
} }

View File

@ -1,35 +1,35 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "JsonParserBase.h" #include "JsonParserBase.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Parser namespace Parser
{ {
// The JSON parser. // The JSON parser.
// //
// You need to specifiy the number of token to be allocated for that parser. // You need to specifiy the number of token to be allocated for that parser.
// //
// CAUTION: JsonArray, JsonObject and JsonValue contain pointers to tokens of the // CAUTION: JsonArray, JsonObject and JsonValue contain pointers to tokens of the
// JsonParser, so they need the JsonParser to be in memory to work. // JsonParser, so they need the JsonParser to be in memory to work.
// As a result, you must not create JsonArray, JsonObject or JsonValue that have a // As a result, you must not create JsonArray, JsonObject or JsonValue that have a
// longer life that the JsonParser. // longer life that the JsonParser.
template <int MAX_TOKENS> template <int MAX_TOKENS>
class JsonParser : public JsonParserBase class JsonParser : public JsonParserBase
{ {
public: public:
JsonParser() JsonParser()
: JsonParserBase(tokens, MAX_TOKENS) : JsonParserBase(tokens, MAX_TOKENS)
{ {
} }
private: private:
jsmntok_t tokens[MAX_TOKENS]; jsmntok_t tokens[MAX_TOKENS];
}; };
} }
} }

View File

@ -1,20 +1,20 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "JsonParserBase.h" #include "JsonParserBase.h"
#include "JsonToken.h" #include "JsonToken.h"
using namespace ArduinoJson::Parser; using namespace ArduinoJson::Parser;
JsonValue JsonParserBase::parse(char* json) JsonValue JsonParserBase::parse(char* json)
{ {
jsmn_parser parser; jsmn_parser parser;
jsmn_init(&parser); jsmn_init(&parser);
if (JSMN_SUCCESS != jsmn_parse(&parser, json, tokens, maxTokens)) if (JSMN_SUCCESS != jsmn_parse(&parser, json, tokens, maxTokens))
return JsonToken::null(); return JsonToken::null();
return JsonToken(json, tokens); return JsonToken(json, tokens);
} }

View File

@ -1,49 +1,49 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "JsonArray.h" #include "JsonArray.h"
#include "JsonObject.h" #include "JsonObject.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Parser namespace Parser
{ {
// Base class for the JSON parser, in case you want to provide your own buffer // Base class for the JSON parser, in case you want to provide your own buffer
class JsonParserBase class JsonParserBase
{ {
public: public:
// Create a JSON parser using the provided buffer // Create a JSON parser using the provided buffer
JsonParserBase(jsmntok_t* tokens, int maxTokens) JsonParserBase(jsmntok_t* tokens, int maxTokens)
: tokens(tokens), maxTokens(maxTokens) : tokens(tokens), maxTokens(maxTokens)
{ {
} }
// Parse the JSON string and return a array // Parse the JSON string and return a array
// //
// The content of the string may be altered to add '\0' at the // The content of the string may be altered to add '\0' at the
// end of string tokens // end of string tokens
JsonValue parse(char* json); JsonValue parse(char* json);
// Obsolete: use parse() instead // Obsolete: use parse() instead
DEPRECATED JsonArray parseArray(char* json) DEPRECATED JsonArray parseArray(char* json)
{ {
return parse(json); return parse(json);
} }
// Obsolete: use parse() instead // Obsolete: use parse() instead
DEPRECATED JsonObject parseHashTable(char* json) DEPRECATED JsonObject parseHashTable(char* json)
{ {
return parse(json); return parse(json);
} }
private: private:
jsmntok_t* tokens; jsmntok_t* tokens;
int maxTokens; int maxTokens;
}; };
} }
} }

View File

@ -1,71 +1,71 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "JsonToken.h" #include "JsonToken.h"
using namespace ArduinoJson::Parser; using namespace ArduinoJson::Parser;
char* JsonToken::getText() char* JsonToken::getText()
{ {
char* s = json + token->start; char* s = json + token->start;
json[token->end] = 0; json[token->end] = 0;
unescapeString(s); unescapeString(s);
return s; return s;
} }
inline void JsonToken::unescapeString(char* s) inline void JsonToken::unescapeString(char* s)
{ {
char* readPtr = s; char* readPtr = s;
char* writePtr = s; char* writePtr = s;
char c; char c;
do do
{ {
c = *readPtr++; c = *readPtr++;
if (c == '\\') if (c == '\\')
{ {
c = unescapeChar(*readPtr++); c = unescapeChar(*readPtr++);
} }
*writePtr++ = c; *writePtr++ = c;
} while (c != 0); } while (c != 0);
} }
inline char JsonToken::unescapeChar(char c) inline char JsonToken::unescapeChar(char c)
{ {
// Optimized for code size on a 8-bit AVR // Optimized for code size on a 8-bit AVR
const char* p = "b\bf\fn\nr\rt\t"; const char* p = "b\bf\fn\nr\rt\t";
while (true) while (true)
{ {
if (p[0] == 0) return c; if (p[0] == 0) return c;
if (p[0] == c) return p[1]; if (p[0] == c) return p[1];
p += 2; p += 2;
} }
} }
JsonToken JsonToken::nextSibling() const JsonToken JsonToken::nextSibling() const
{ {
// start with current token // start with current token
jsmntok_t* t = token; jsmntok_t* t = token;
// count the number of token to skip // count the number of token to skip
int yetToVisit = 1; int yetToVisit = 1;
// skip all nested tokens // skip all nested tokens
while (yetToVisit) while (yetToVisit)
{ {
yetToVisit += t->size - 1; yetToVisit += t->size - 1;
t++; t++;
} }
// build a JsonToken at the new location // build a JsonToken at the new location
return JsonToken(json, t); return JsonToken(json, t);
} }

View File

@ -1,99 +1,99 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "jsmn.h" #include "jsmn.h"
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Parser namespace Parser
{ {
// A pointer to a JSON token // A pointer to a JSON token
class JsonToken class JsonToken
{ {
public: public:
// Create a "null" pointer // Create a "null" pointer
JsonToken() JsonToken()
: token(0) : token(0)
{ {
} }
// Create a pointer to the specified JSON token // Create a pointer to the specified JSON token
JsonToken(char* json, jsmntok_t* token) JsonToken(char* json, jsmntok_t* token)
: json(json), token(token) : json(json), token(token)
{ {
} }
// Get content of the JSON token // Get content of the JSON token
char* getText(); char* getText();
// Get the number of children tokens // Get the number of children tokens
int childrenCount() int childrenCount()
{ {
return token->size; return token->size;
} }
// Get a pointer to the first child of the current token // Get a pointer to the first child of the current token
JsonToken firstChild() const JsonToken firstChild() const
{ {
return JsonToken(json, token + 1); return JsonToken(json, token + 1);
} }
// Get a pointer to the next sibling token (ie skiping the children tokens) // Get a pointer to the next sibling token (ie skiping the children tokens)
JsonToken nextSibling() const; JsonToken nextSibling() const;
// Test equality // Test equality
bool operator!=(const JsonToken& other) const bool operator!=(const JsonToken& other) const
{ {
return token != other.token; return token != other.token;
} }
// Tell if the pointer is "null" // Tell if the pointer is "null"
bool isValid() bool isValid()
{ {
return token != 0; return token != 0;
} }
// Tell if the JSON token is a JSON object // Tell if the JSON token is a JSON object
bool isObject() bool isObject()
{ {
return token != 0 && token->type == JSMN_OBJECT; return token != 0 && token->type == JSMN_OBJECT;
} }
// Tell if the JSON token is a JSON array // Tell if the JSON token is a JSON array
bool isArray() bool isArray()
{ {
return token != 0 && token->type == JSMN_ARRAY; return token != 0 && token->type == JSMN_ARRAY;
} }
// Tell if the JSON token is a primitive // Tell if the JSON token is a primitive
bool isPrimitive() bool isPrimitive()
{ {
return token != 0 && token->type == JSMN_PRIMITIVE; return token != 0 && token->type == JSMN_PRIMITIVE;
} }
// Tell if the JSON token is a string // Tell if the JSON token is a string
bool isString() bool isString()
{ {
return token != 0 && token->type == JSMN_STRING; return token != 0 && token->type == JSMN_STRING;
} }
// Explicit wait to create a "null" JsonToken // Explicit wait to create a "null" JsonToken
static JsonToken null() static JsonToken null()
{ {
return JsonToken(); return JsonToken();
} }
private: private:
char* json; char* json;
jsmntok_t* token; jsmntok_t* token;
static char unescapeChar(char c); static char unescapeChar(char c);
static void unescapeString(char* s); static void unescapeString(char* s);
}; };
} }
} }

View File

@ -1,110 +1,110 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include <stdlib.h> // for strtol, strtod #include <stdlib.h> // for strtol, strtod
#include <string.h> // for strcmp() #include <string.h> // for strcmp()
#include "JsonArray.h" #include "JsonArray.h"
#include "JsonObject.h" #include "JsonObject.h"
#include "JsonValue.h" #include "JsonValue.h"
using namespace ArduinoJson::Parser; using namespace ArduinoJson::Parser;
// Convert the JsonValue to a bool. // Convert the JsonValue to a bool.
// Returns false if the JsonValue is not a primitve. // Returns false if the JsonValue is not a primitve.
JsonValue::operator bool() JsonValue::operator bool()
{ {
if (!isPrimitive()) return 0; if (!isPrimitive()) return 0;
char *text = getText(); char *text = getText();
// "true" // "true"
if (text[0] == 't') return true; if (text[0] == 't') return true;
// "false" // "false"
if (text[0] == 'f') return false; if (text[0] == 'f') return false;
// "null" // "null"
if (text[0] == 'n') return false; if (text[0] == 'n') return false;
// number // number
return strtol(text, 0, 0) != 0; return strtol(text, 0, 0) != 0;
} }
// Convert the JsonValue to a floating point value. // Convert the JsonValue to a floating point value.
// Returns false if the JsonValue is not a number. // Returns false if the JsonValue is not a number.
JsonValue::operator double() JsonValue::operator double()
{ {
return isPrimitive() ? strtod(getText(), 0) : 0; return isPrimitive() ? strtod(getText(), 0) : 0;
} }
// Convert the JsonValue to a floating point value. // Convert the JsonValue to a floating point value.
// Returns false if the JsonValue is not a number. // Returns false if the JsonValue is not a number.
JsonValue::operator long() JsonValue::operator long()
{ {
return isPrimitive() ? strtol(getText(), 0, 0) : 0; return isPrimitive() ? strtol(getText(), 0, 0) : 0;
} }
// Convert the JsonValue to a string. // Convert the JsonValue to a string.
// Returns 0 if the JsonValue is not a string. // Returns 0 if the JsonValue is not a string.
JsonValue::operator char*() JsonValue::operator char*()
{ {
return isString() || isPrimitive() ? getText() : 0; return isString() || isPrimitive() ? getText() : 0;
} }
// Get the nested value at the specified index. // Get the nested value at the specified index.
// Returns an invalid JsonValue if the current value is not an array. // Returns an invalid JsonValue if the current value is not an array.
JsonValue JsonValue::operator[](int index) JsonValue JsonValue::operator[](int index)
{ {
// sanity check // sanity check
if (index < 0 || !isArray() || index >= childrenCount()) if (index < 0 || !isArray() || index >= childrenCount())
return null(); return null();
// skip first token, it's the whole object // skip first token, it's the whole object
JsonToken runningToken = firstChild(); JsonToken runningToken = firstChild();
// skip all tokens before the specified index // skip all tokens before the specified index
for (int i = 0; i < index; i++) for (int i = 0; i < index; i++)
{ {
// move forward: current + nested tokens // move forward: current + nested tokens
runningToken = runningToken.nextSibling(); runningToken = runningToken.nextSibling();
} }
return runningToken; return runningToken;
} }
// Get the nested value matching the specified index. // Get the nested value matching the specified index.
// Returns an invalid JsonValue if the current value is not an object. // Returns an invalid JsonValue if the current value is not an object.
JsonValue JsonValue::operator[](const char* desiredKey) JsonValue JsonValue::operator[](const char* desiredKey)
{ {
// sanity check // sanity check
if (desiredKey == 0 || !isObject()) if (desiredKey == 0 || !isObject())
return null(); return null();
// skip first token, it's the whole object // skip first token, it's the whole object
JsonToken runningToken = firstChild(); JsonToken runningToken = firstChild();
// scan each keys // scan each keys
for (int i = 0; i < childrenCount() / 2; i++) for (int i = 0; i < childrenCount() / 2; i++)
{ {
// get 'key' token string // get 'key' token string
char* key = runningToken.getText(); char* key = runningToken.getText();
// move to the 'value' token // move to the 'value' token
runningToken = runningToken.nextSibling(); runningToken = runningToken.nextSibling();
// compare with desired name // compare with desired name
if (strcmp(desiredKey, key) == 0) if (strcmp(desiredKey, key) == 0)
{ {
// return the value token that follows the key token // return the value token that follows the key token
return runningToken; return runningToken;
} }
// skip nested tokens // skip nested tokens
runningToken = runningToken.nextSibling(); runningToken = runningToken.nextSibling();
} }
// nothing found, return NULL // nothing found, return NULL
return null(); return null();
} }

View File

@ -1,72 +1,72 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#pragma once #pragma once
#include "JsonToken.h" #include "JsonToken.h"
#ifndef ARDUINO_JSON_NO_DEPRECATION_WARNING #ifndef ARDUINO_JSON_NO_DEPRECATION_WARNING
#ifdef __GNUC__ #ifdef __GNUC__
#define DEPRECATED __attribute__((deprecated)) #define DEPRECATED __attribute__((deprecated))
#elif defined(_MSC_VER) #elif defined(_MSC_VER)
#define DEPRECATED __declspec(deprecated) #define DEPRECATED __declspec(deprecated)
#endif #endif
#else #else
#define DEPRECATED #define DEPRECATED
#endif #endif
namespace ArduinoJson namespace ArduinoJson
{ {
namespace Parser namespace Parser
{ {
// A JSON value // A JSON value
// Can be converted to string, double, bool, array or object. // Can be converted to string, double, bool, array or object.
class JsonValue : protected JsonToken class JsonValue : protected JsonToken
{ {
public: public:
// Create a invalid value // Create a invalid value
JsonValue() JsonValue()
{ {
} }
// Convert a JsonToken to a JsonValue // Convert a JsonToken to a JsonValue
JsonValue(JsonToken token) JsonValue(JsonToken token)
: JsonToken(token) : JsonToken(token)
{ {
} }
// Tell is the JsonValue is valid // Tell is the JsonValue is valid
bool success() bool success()
{ {
return isValid(); return isValid();
} }
// Convert the JsonValue to a bool. // Convert the JsonValue to a bool.
// Returns false if the JsonValue is not a primitve. // Returns false if the JsonValue is not a primitve.
operator bool(); operator bool();
// Convert the JsonValue to a floating point value. // Convert the JsonValue to a floating point value.
// Returns false if the JsonValue is not a number. // Returns false if the JsonValue is not a number.
operator double(); operator double();
// Convert the JsonValue to a long integer. // Convert the JsonValue to a long integer.
// Returns 0 if the JsonValue is not a number. // Returns 0 if the JsonValue is not a number.
operator long(); operator long();
// Convert the JsonValue to a string. // Convert the JsonValue to a string.
// Returns 0 if the JsonValue is not a string. // Returns 0 if the JsonValue is not a string.
operator char*(); operator char*();
// Get the nested value at the specified index. // Get the nested value at the specified index.
// Returns an invalid JsonValue if the current value is not an array. // Returns an invalid JsonValue if the current value is not an array.
JsonValue operator[](int index); JsonValue operator[](int index);
// Get the nested value matching the specified index. // Get the nested value matching the specified index.
// Returns an invalid JsonValue if the current value is not an object. // Returns an invalid JsonValue if the current value is not an object.
JsonValue operator[](const char* key); JsonValue operator[](const char* key);
}; };
} }
} }

View File

@ -1,244 +1,244 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "JsonParser.h" #include "JsonParser.h"
#include <string> #include <string>
using namespace std; using namespace std;
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace ArduinoJson::Parser; using namespace ArduinoJson::Parser;
namespace ArduinoJsonParserTests namespace ArduinoJsonParserTests
{ {
TEST_CLASS(GbathreeBug) TEST_CLASS(GbathreeBug)
{ {
char json[1024]; char json[1024];
JsonParser<200> parser; JsonParser<200> parser;
JsonHashTable root; JsonHashTable root;
public: public:
TEST_METHOD_INITIALIZE(Initialize) TEST_METHOD_INITIALIZE(Initialize)
{ {
// BUG described here: // BUG described here:
// http://forum.arduino.cc/index.php?topic=172578.msg1608219#msg1608219 // http://forum.arduino.cc/index.php?topic=172578.msg1608219#msg1608219
strcpy(json, "{ \"protocol_name\":\"fluorescence\",\"repeats\":1,\"wait\":0,\"averages\":1,\"measurements\":3,\"meas2_light\":15,\"meas1_baseline\":0,\"act_light\":20,\"pulsesize\":25,\"pulsedistance\":10000,\"actintensity1\":50,\"actintensity2\":255,\"measintensity\":255,\"calintensity\":255,\"pulses\":[50,50,50],\"act\":[2,1,2,2],\"red\":[2,2,2,2],\"detectors\":[[34,34,34,34],[34,34,34,34],[34,34,34,34],[34,34,34,34]],\"alta\":[2,2,2,2],\"altb\":[2,2,2,2],\"measlights\":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]],\"measlights2\":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]],\"altc\":[2,2,2,2],\"altd\":[2,2,2,2]}"); strcpy(json, "{ \"protocol_name\":\"fluorescence\",\"repeats\":1,\"wait\":0,\"averages\":1,\"measurements\":3,\"meas2_light\":15,\"meas1_baseline\":0,\"act_light\":20,\"pulsesize\":25,\"pulsedistance\":10000,\"actintensity1\":50,\"actintensity2\":255,\"measintensity\":255,\"calintensity\":255,\"pulses\":[50,50,50],\"act\":[2,1,2,2],\"red\":[2,2,2,2],\"detectors\":[[34,34,34,34],[34,34,34,34],[34,34,34,34],[34,34,34,34]],\"alta\":[2,2,2,2],\"altb\":[2,2,2,2],\"measlights\":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]],\"measlights2\":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]],\"altc\":[2,2,2,2],\"altd\":[2,2,2,2]}");
root = parser.parseHashTable(json); root = parser.parseHashTable(json);
} }
TEST_METHOD(Root) TEST_METHOD(Root)
{ {
Assert::IsTrue(root.success()); Assert::IsTrue(root.success());
} }
TEST_METHOD(ProtocolName) TEST_METHOD(ProtocolName)
{ {
string protocol_name = root.getString("protocol_name"); string protocol_name = root.getString("protocol_name");
Assert::AreEqual(string("fluorescence"), protocol_name); Assert::AreEqual(string("fluorescence"), protocol_name);
} }
TEST_METHOD(Repeats) TEST_METHOD(Repeats)
{ {
Assert::AreEqual(1L, root.getLong("repeats")); Assert::AreEqual(1L, root.getLong("repeats"));
} }
TEST_METHOD(Wait) TEST_METHOD(Wait)
{ {
Assert::AreEqual(0L, root.getLong("wait")); Assert::AreEqual(0L, root.getLong("wait"));
} }
TEST_METHOD(Measurements) TEST_METHOD(Measurements)
{ {
Assert::AreEqual(3L, root.getLong("measurements")); Assert::AreEqual(3L, root.getLong("measurements"));
} }
TEST_METHOD(Meas2_Light) TEST_METHOD(Meas2_Light)
{ {
Assert::AreEqual(15L, root.getLong("meas2_light")); Assert::AreEqual(15L, root.getLong("meas2_light"));
} }
TEST_METHOD(Meas1_Baseline) TEST_METHOD(Meas1_Baseline)
{ {
Assert::AreEqual(0L, root.getLong("meas1_baseline")); Assert::AreEqual(0L, root.getLong("meas1_baseline"));
} }
TEST_METHOD(Act_Light) TEST_METHOD(Act_Light)
{ {
Assert::AreEqual(20L, root.getLong("act_light")); Assert::AreEqual(20L, root.getLong("act_light"));
} }
TEST_METHOD(Pulsesize) TEST_METHOD(Pulsesize)
{ {
Assert::AreEqual(25L, root.getLong("pulsesize")); Assert::AreEqual(25L, root.getLong("pulsesize"));
} }
TEST_METHOD(Pulsedistance) TEST_METHOD(Pulsedistance)
{ {
Assert::AreEqual(10000L, root.getLong("pulsedistance")); Assert::AreEqual(10000L, root.getLong("pulsedistance"));
} }
TEST_METHOD(Actintensity1) TEST_METHOD(Actintensity1)
{ {
Assert::AreEqual(50L, root.getLong("actintensity1")); Assert::AreEqual(50L, root.getLong("actintensity1"));
} }
TEST_METHOD(Actintensity2) TEST_METHOD(Actintensity2)
{ {
Assert::AreEqual(255L, root.getLong("actintensity2")); Assert::AreEqual(255L, root.getLong("actintensity2"));
} }
TEST_METHOD(Measintensity) TEST_METHOD(Measintensity)
{ {
Assert::AreEqual(255L, root.getLong("measintensity")); Assert::AreEqual(255L, root.getLong("measintensity"));
} }
TEST_METHOD(Calintensity) TEST_METHOD(Calintensity)
{ {
Assert::AreEqual(255L, root.getLong("calintensity")); Assert::AreEqual(255L, root.getLong("calintensity"));
} }
TEST_METHOD(Pulses) TEST_METHOD(Pulses)
{ {
// "pulses":[50,50,50] // "pulses":[50,50,50]
JsonArray array = root.getArray("pulses"); JsonArray array = root.getArray("pulses");
Assert::IsTrue(array.success()); Assert::IsTrue(array.success());
Assert::AreEqual(3, array.getLength()); Assert::AreEqual(3, array.getLength());
for (int i = 0; i < 3; i++) for (int i = 0; i < 3; i++)
{ {
Assert::AreEqual(50L, array.getLong(i)); Assert::AreEqual(50L, array.getLong(i));
} }
} }
TEST_METHOD(Act) TEST_METHOD(Act)
{ {
// "act":[2,1,2,2] // "act":[2,1,2,2]
JsonArray array = root.getArray("act"); JsonArray array = root.getArray("act");
Assert::IsTrue(array.success()); Assert::IsTrue(array.success());
Assert::AreEqual(4, array.getLength()); Assert::AreEqual(4, array.getLength());
Assert::AreEqual(2L, array.getLong(0)); Assert::AreEqual(2L, array.getLong(0));
Assert::AreEqual(1L, array.getLong(1)); Assert::AreEqual(1L, array.getLong(1));
Assert::AreEqual(2L, array.getLong(2)); Assert::AreEqual(2L, array.getLong(2));
Assert::AreEqual(2L, array.getLong(3)); Assert::AreEqual(2L, array.getLong(3));
} }
TEST_METHOD(Detectors) TEST_METHOD(Detectors)
{ {
// "detectors":[[34,34,34,34],[34,34,34,34],[34,34,34,34],[34,34,34,34]] // "detectors":[[34,34,34,34],[34,34,34,34],[34,34,34,34],[34,34,34,34]]
JsonArray array = root.getArray("detectors"); JsonArray array = root.getArray("detectors");
Assert::IsTrue(array.success()); Assert::IsTrue(array.success());
Assert::AreEqual(4, array.getLength()); Assert::AreEqual(4, array.getLength());
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
{ {
Assert::AreEqual(4, array.getArray(i).getLength()); Assert::AreEqual(4, array.getArray(i).getLength());
for (int j = 0; j < 4; j++) for (int j = 0; j < 4; j++)
Assert::AreEqual(34L, array.getArray(i).getLong(j)); Assert::AreEqual(34L, array.getArray(i).getLong(j));
} }
} }
TEST_METHOD(Alta) TEST_METHOD(Alta)
{ {
// alta:[2,2,2,2] // alta:[2,2,2,2]
JsonArray array = root.getArray("alta"); JsonArray array = root.getArray("alta");
Assert::IsTrue(array.success()); Assert::IsTrue(array.success());
Assert::AreEqual(4, array.getLength()); Assert::AreEqual(4, array.getLength());
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
{ {
Assert::AreEqual(2L, array.getLong(i)); Assert::AreEqual(2L, array.getLong(i));
} }
} }
TEST_METHOD(Altb) TEST_METHOD(Altb)
{ {
// altb:[2,2,2,2] // altb:[2,2,2,2]
JsonArray array = root.getArray("altb"); JsonArray array = root.getArray("altb");
Assert::IsTrue(array.success()); Assert::IsTrue(array.success());
Assert::AreEqual(4, array.getLength()); Assert::AreEqual(4, array.getLength());
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
{ {
Assert::AreEqual(2L, array.getLong(i)); Assert::AreEqual(2L, array.getLong(i));
} }
} }
TEST_METHOD(Measlights) TEST_METHOD(Measlights)
{ {
// "measlights":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]] // "measlights":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]]
JsonArray array = root.getArray("measlights"); JsonArray array = root.getArray("measlights");
Assert::IsTrue(array.success()); Assert::IsTrue(array.success());
Assert::AreEqual(4, array.getLength()); Assert::AreEqual(4, array.getLength());
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
{ {
Assert::AreEqual(4, array.getArray(i).getLength()); Assert::AreEqual(4, array.getArray(i).getLength());
for (int j = 0; j < 4; j++) for (int j = 0; j < 4; j++)
Assert::AreEqual(15L, array.getArray(i).getLong(j)); Assert::AreEqual(15L, array.getArray(i).getLong(j));
} }
} }
TEST_METHOD(Measlights2) TEST_METHOD(Measlights2)
{ {
// "measlights2":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]] // "measlights2":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]]
JsonArray array = root.getArray("measlights2"); JsonArray array = root.getArray("measlights2");
Assert::IsTrue(array.success()); Assert::IsTrue(array.success());
Assert::AreEqual(4, array.getLength()); Assert::AreEqual(4, array.getLength());
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
{ {
Assert::AreEqual(4, array.getArray(i).getLength()); Assert::AreEqual(4, array.getArray(i).getLength());
for (int j = 0; j < 4; j++) for (int j = 0; j < 4; j++)
Assert::AreEqual(15L, array.getArray(i).getLong(j)); Assert::AreEqual(15L, array.getArray(i).getLong(j));
} }
} }
TEST_METHOD(Altc) TEST_METHOD(Altc)
{ {
// altc:[2,2,2,2] // altc:[2,2,2,2]
JsonArray array = root.getArray("altc"); JsonArray array = root.getArray("altc");
Assert::IsTrue(array.success()); Assert::IsTrue(array.success());
Assert::AreEqual(4, array.getLength()); Assert::AreEqual(4, array.getLength());
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
{ {
Assert::AreEqual(2L, array.getLong(i)); Assert::AreEqual(2L, array.getLong(i));
} }
} }
TEST_METHOD(Altd) TEST_METHOD(Altd)
{ {
// altd:[2,2,2,2] // altd:[2,2,2,2]
JsonArray array = root.getArray("altd"); JsonArray array = root.getArray("altd");
Assert::IsTrue(array.success()); Assert::IsTrue(array.success());
Assert::AreEqual(4, array.getLength()); Assert::AreEqual(4, array.getLength());
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
{ {
Assert::AreEqual(2L, array.getLong(i)); Assert::AreEqual(2L, array.getLong(i));
} }
} }
}; };
} }

View File

@ -1,67 +1,67 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "JsonParser.h" #include "JsonParser.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace ArduinoJson::Parser; using namespace ArduinoJson::Parser;
namespace JsonParserTests namespace JsonParserTests
{ {
TEST_CLASS(JsonArrayIteratorTests) TEST_CLASS(JsonArrayIteratorTests)
{ {
public: public:
TEST_METHOD(EmptyJson) TEST_METHOD(EmptyJson)
{ {
char json[] = ""; char json[] = "";
JsonParser<1> parser; JsonParser<1> parser;
JsonArray a = parser.parse(json); JsonArray a = parser.parse(json);
int loopCount = 0; int loopCount = 0;
for (long i : a) for (long i : a)
{ {
loopCount++; loopCount++;
} }
Assert::AreEqual(0, loopCount); Assert::AreEqual(0, loopCount);
} }
TEST_METHOD(ThreeIntegers) TEST_METHOD(ThreeIntegers)
{ {
char json [] = "[1,2,3]"; char json [] = "[1,2,3]";
long expected [] = {1, 2, 3}; long expected [] = {1, 2, 3};
JsonParser<4> parser; JsonParser<4> parser;
JsonArray a = parser.parse(json); JsonArray a = parser.parse(json);
int index = 0; int index = 0;
for (long i : a) for (long i : a)
{ {
Assert::AreEqual(expected[index++], i); Assert::AreEqual(expected[index++], i);
} }
} }
TEST_METHOD(ThreeStrings) TEST_METHOD(ThreeStrings)
{ {
char json[] = "[\"1\",\"2\",\"3\"]"; char json[] = "[\"1\",\"2\",\"3\"]";
char* expected[] = {"1", "2", "3"}; char* expected[] = {"1", "2", "3"};
JsonParser<4> parser; JsonParser<4> parser;
JsonArray a = parser.parse(json); JsonArray a = parser.parse(json);
int index = 0; int index = 0;
for (const char* i : a) for (const char* i : a)
{ {
Assert::AreEqual(expected[index++], i); Assert::AreEqual(expected[index++], i);
} }
} }
}; };
} }

View File

@ -1,181 +1,181 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "JsonParser.h" #include "JsonParser.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace ArduinoJson::Parser; using namespace ArduinoJson::Parser;
namespace ArduinoJsonParserTests namespace ArduinoJsonParserTests
{ {
TEST_CLASS(JsonArrayTests) TEST_CLASS(JsonArrayTests)
{ {
JsonArray array; JsonArray array;
char json[256]; char json[256];
jsmntok_t tokens[32]; jsmntok_t tokens[32];
JsonParserBase parser = JsonParserBase(tokens, 32); JsonParserBase parser = JsonParserBase(tokens, 32);
public: public:
TEST_METHOD(TooFewClosingBrackets) TEST_METHOD(TooFewClosingBrackets)
{ {
whenInputIs("[[]"); whenInputIs("[[]");
parseMustFail(); parseMustFail();
} }
TEST_METHOD(TooManyClosingBrackets) TEST_METHOD(TooManyClosingBrackets)
{ {
whenInputIs("[]]"); whenInputIs("[]]");
parseMustFail(); parseMustFail();
} }
TEST_METHOD(EmptyArray) TEST_METHOD(EmptyArray)
{ {
whenInputIs("[]"); whenInputIs("[]");
parseMustSucceed(); parseMustSucceed();
lengthMustBe(0); lengthMustBe(0);
} }
TEST_METHOD(NotEnoughTokens) TEST_METHOD(NotEnoughTokens)
{ {
setTokenCountTo(2); setTokenCountTo(2);
whenInputIs("[1,2]"); whenInputIs("[1,2]");
parseMustFail(); parseMustFail();
itemMustNotExist(0); itemMustNotExist(0);
} }
TEST_METHOD(TwoIntegers) TEST_METHOD(TwoIntegers)
{ {
setTokenCountTo(3); setTokenCountTo(3);
whenInputIs("[1,2]"); whenInputIs("[1,2]");
parseMustSucceed(); parseMustSucceed();
lengthMustBe(2); lengthMustBe(2);
itemMustBe(0, 1L); itemMustBe(0, 1L);
itemMustBe(1, 2L); itemMustBe(1, 2L);
itemMustNotExist(2); itemMustNotExist(2);
} }
TEST_METHOD(TwoBooleans) TEST_METHOD(TwoBooleans)
{ {
setTokenCountTo(3); setTokenCountTo(3);
whenInputIs("[true,false]"); whenInputIs("[true,false]");
parseMustSucceed(); parseMustSucceed();
lengthMustBe(2); lengthMustBe(2);
itemMustBe(0, true); itemMustBe(0, true);
itemMustBe(1, false); itemMustBe(1, false);
itemMustNotExist(2); itemMustNotExist(2);
} }
TEST_METHOD(TwoStrings) TEST_METHOD(TwoStrings)
{ {
setTokenCountTo(3); setTokenCountTo(3);
whenInputIs("[\"hello\",\"world\"]"); whenInputIs("[\"hello\",\"world\"]");
parseMustSucceed(); parseMustSucceed();
lengthMustBe(2); lengthMustBe(2);
itemMustBe(0, "hello"); itemMustBe(0, "hello");
itemMustBe(1, "world"); itemMustBe(1, "world");
itemMustNotExist(2); itemMustNotExist(2);
} }
TEST_METHOD(TwoDimensionsArray) TEST_METHOD(TwoDimensionsArray)
{ {
setTokenCountTo(7); setTokenCountTo(7);
whenInputIs("[[1,2],[3,4]]"); whenInputIs("[[1,2],[3,4]]");
parseMustSucceed(); parseMustSucceed();
lengthMustBe(2); lengthMustBe(2);
itemMustBe(0, 0, 1L); itemMustBe(0, 0, 1L);
itemMustBe(0, 1, 2L); itemMustBe(0, 1, 2L);
itemMustBe(1, 0, 3L); itemMustBe(1, 0, 3L);
itemMustBe(1, 1, 4L); itemMustBe(1, 1, 4L);
itemMustNotExist(2); itemMustNotExist(2);
} }
TEST_METHOD(ThreeDimensionsArray) TEST_METHOD(ThreeDimensionsArray)
{ {
setTokenCountTo(15); setTokenCountTo(15);
whenInputIs("[[[1,2],[3,4]],[[5,6],[7,8]]]"); whenInputIs("[[[1,2],[3,4]],[[5,6],[7,8]]]");
parseMustSucceed(); parseMustSucceed();
lengthMustBe(2); lengthMustBe(2);
itemMustBe(0, 0, 0, 1L); itemMustBe(0, 0, 0, 1L);
itemMustBe(0, 0, 1, 2L); itemMustBe(0, 0, 1, 2L);
itemMustBe(0, 1, 0, 3L); itemMustBe(0, 1, 0, 3L);
itemMustBe(0, 1, 1, 4L); itemMustBe(0, 1, 1, 4L);
itemMustBe(1, 0, 0, 5L); itemMustBe(1, 0, 0, 5L);
itemMustBe(1, 0, 1, 6L); itemMustBe(1, 0, 1, 6L);
itemMustBe(1, 1, 0, 7L); itemMustBe(1, 1, 0, 7L);
itemMustBe(1, 1, 1, 8L); itemMustBe(1, 1, 1, 8L);
itemMustNotExist(2); itemMustNotExist(2);
} }
private: private:
void setTokenCountTo(int n) void setTokenCountTo(int n)
{ {
parser = JsonParserBase(tokens, n); parser = JsonParserBase(tokens, n);
} }
void whenInputIs(const char* input) void whenInputIs(const char* input)
{ {
strcpy(json, input); strcpy(json, input);
array = parser.parseArray(json); array = parser.parseArray(json);
} }
void parseMustFail() void parseMustFail()
{ {
Assert::IsFalse(array.success()); Assert::IsFalse(array.success());
lengthMustBe(0); lengthMustBe(0);
} }
void parseMustSucceed() void parseMustSucceed()
{ {
Assert::IsTrue(array.success()); Assert::IsTrue(array.success());
} }
void lengthMustBe(int expected) void lengthMustBe(int expected)
{ {
Assert::AreEqual(expected, array.getLength()); Assert::AreEqual(expected, array.getLength());
} }
void itemMustBe(int index, long expected) void itemMustBe(int index, long expected)
{ {
Assert::AreEqual(expected, array.getLong(index)); Assert::AreEqual(expected, array.getLong(index));
} }
void itemMustBe(int index, bool expected) void itemMustBe(int index, bool expected)
{ {
Assert::AreEqual(expected, array.getBool(index)); Assert::AreEqual(expected, array.getBool(index));
} }
void itemMustBe(int index, const char* expected) void itemMustBe(int index, const char* expected)
{ {
Assert::AreEqual(expected, array.getString(index)); Assert::AreEqual(expected, array.getString(index));
} }
void itemMustBe(int index0, int index1, long expected) void itemMustBe(int index0, int index1, long expected)
{ {
Assert::AreEqual(expected, array.getArray(index0).getLong(index1)); Assert::AreEqual(expected, array.getArray(index0).getLong(index1));
} }
void itemMustBe(int index0, int index1, int index2, long expected) void itemMustBe(int index0, int index1, int index2, long expected)
{ {
Assert::AreEqual(expected, array.getArray(index0).getArray(index1).getLong(index2)); Assert::AreEqual(expected, array.getArray(index0).getArray(index1).getLong(index2));
} }
void itemMustNotExist(int index) void itemMustNotExist(int index)
{ {
Assert::IsFalse(array.getHashTable(index).success()); Assert::IsFalse(array.getHashTable(index).success());
@ -184,6 +184,6 @@ namespace ArduinoJsonParserTests
Assert::AreEqual(0.0, array.getDouble(index)); Assert::AreEqual(0.0, array.getDouble(index));
Assert::AreEqual(0L, array.getLong(index)); Assert::AreEqual(0L, array.getLong(index));
Assert::IsNull(array.getString(index)); Assert::IsNull(array.getString(index));
} }
}; };
} }

View File

@ -1,71 +1,71 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "JsonParser.h" #include "JsonParser.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace ArduinoJson::Parser; using namespace ArduinoJson::Parser;
namespace JsonParserTests namespace JsonParserTests
{ {
TEST_CLASS(JsonObjectIteratorTests) TEST_CLASS(JsonObjectIteratorTests)
{ {
public: public:
TEST_METHOD(EmptyObject) TEST_METHOD(EmptyObject)
{ {
char json [] = "{}"; char json [] = "{}";
JsonParser<1> parser; JsonParser<1> parser;
JsonHashTable a = parser.parse(json); JsonHashTable a = parser.parse(json);
int loopCount = 0; int loopCount = 0;
for (auto i : a) for (auto i : a)
{ {
loopCount++; loopCount++;
} }
Assert::AreEqual(0, loopCount); Assert::AreEqual(0, loopCount);
} }
TEST_METHOD(EmptyJson) TEST_METHOD(EmptyJson)
{ {
char json[] = ""; char json[] = "";
JsonParser<1> parser; JsonParser<1> parser;
JsonHashTable a = parser.parse(json); JsonHashTable a = parser.parse(json);
int loopCount = 0; int loopCount = 0;
for (auto i : a) for (auto i : a)
{ {
loopCount++; loopCount++;
} }
Assert::AreEqual(0, loopCount); Assert::AreEqual(0, loopCount);
} }
TEST_METHOD(ThreeStrings) TEST_METHOD(ThreeStrings)
{ {
char json[] = "{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\"}"; char json[] = "{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\"}";
char* expectedKeys[] = {"key1", "key2", "key3"}; char* expectedKeys[] = {"key1", "key2", "key3"};
char* expectedValues[] = {"value1", "value2", "value3"}; char* expectedValues[] = {"value1", "value2", "value3"};
JsonParser<7> parser; JsonParser<7> parser;
JsonHashTable a = parser.parse(json); JsonHashTable a = parser.parse(json);
int index = 0; int index = 0;
for (auto i : a) for (auto i : a)
{ {
Assert::AreEqual(expectedKeys[index], i.key()); Assert::AreEqual(expectedKeys[index], i.key());
Assert::AreEqual(expectedValues[index], (const char*) i.value()); Assert::AreEqual(expectedValues[index], (const char*) i.value());
index++; index++;
} }
} }
}; };
} }

View File

@ -1,165 +1,165 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "JsonParser.h" #include "JsonParser.h"
#include <string> #include <string>
using namespace std; using namespace std;
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace ArduinoJson::Parser; using namespace ArduinoJson::Parser;
namespace ArduinoJsonParserTests namespace ArduinoJsonParserTests
{ {
TEST_CLASS(JsonHashTableTests) TEST_CLASS(JsonHashTableTests)
{ {
JsonHashTable hashTable; JsonHashTable hashTable;
JsonArray nestedArray; JsonArray nestedArray;
char json[256]; char json[256];
jsmntok_t tokens[32]; jsmntok_t tokens[32];
JsonParserBase parser = JsonParserBase(tokens, 32); JsonParserBase parser = JsonParserBase(tokens, 32);
public: public:
TEST_METHOD(EmptyHashTable) TEST_METHOD(EmptyHashTable)
{ {
whenInputIs("{}"); whenInputIs("{}");
parseMustSucceed(); parseMustSucceed();
} }
TEST_METHOD(NotEnoughTokens) TEST_METHOD(NotEnoughTokens)
{ {
setTokenCountTo(2); setTokenCountTo(2);
whenInputIs("{\"key\":0}"); whenInputIs("{\"key\":0}");
parseMustFail(); parseMustFail();
itemMustNotExist("key"); itemMustNotExist("key");
} }
TEST_METHOD(TwoIntegers) TEST_METHOD(TwoIntegers)
{ {
setTokenCountTo(5); setTokenCountTo(5);
whenInputIs("{\"key1\":1,\"key2\":2}"); whenInputIs("{\"key1\":1,\"key2\":2}");
parseMustSucceed(); parseMustSucceed();
itemMustBe("key1", 1L); itemMustBe("key1", 1L);
itemMustBe("key2", 2L); itemMustBe("key2", 2L);
itemMustNotExist("key3"); itemMustNotExist("key3");
} }
TEST_METHOD(TwoBooleans) TEST_METHOD(TwoBooleans)
{ {
setTokenCountTo(5); setTokenCountTo(5);
whenInputIs("{\"key1\":true,\"key2\":false}"); whenInputIs("{\"key1\":true,\"key2\":false}");
parseMustSucceed(); parseMustSucceed();
itemMustBe("key1", true); itemMustBe("key1", true);
itemMustBe("key2", false); itemMustBe("key2", false);
itemMustNotExist("key3"); itemMustNotExist("key3");
} }
TEST_METHOD(TwoStrings) TEST_METHOD(TwoStrings)
{ {
setTokenCountTo(5); setTokenCountTo(5);
whenInputIs("{\"key1\":\"hello\",\"key2\":\"world\"}"); whenInputIs("{\"key1\":\"hello\",\"key2\":\"world\"}");
parseMustSucceed(); parseMustSucceed();
itemMustBe("key1", "hello"); itemMustBe("key1", "hello");
itemMustBe("key2", "world"); itemMustBe("key2", "world");
itemMustNotExist("key3"); itemMustNotExist("key3");
} }
TEST_METHOD(TwoNestedArrays) TEST_METHOD(TwoNestedArrays)
{ {
setTokenCountTo(9); setTokenCountTo(9);
whenInputIs("{\"key1\":[1,2],\"key2\":[3,4]}"); whenInputIs("{\"key1\":[1,2],\"key2\":[3,4]}");
parseMustSucceed(); parseMustSucceed();
itemMustBeAnArray("key1"); itemMustBeAnArray("key1");
arrayLengthMustBe(2); arrayLengthMustBe(2);
arrayItemMustBe(0, 1L); arrayItemMustBe(0, 1L);
arrayItemMustBe(1, 2L); arrayItemMustBe(1, 2L);
arrayItemMustBe(2, 0L); arrayItemMustBe(2, 0L);
itemMustBeAnArray("key2"); itemMustBeAnArray("key2");
arrayLengthMustBe(2); arrayLengthMustBe(2);
arrayItemMustBe(0, 3L); arrayItemMustBe(0, 3L);
arrayItemMustBe(1, 4L); arrayItemMustBe(1, 4L);
arrayItemMustBe(2, 0L); arrayItemMustBe(2, 0L);
itemMustNotExist("key3"); itemMustNotExist("key3");
} }
private: private:
void setTokenCountTo(int n) void setTokenCountTo(int n)
{ {
parser = JsonParserBase(tokens, n); parser = JsonParserBase(tokens, n);
} }
void whenInputIs(const char* input) void whenInputIs(const char* input)
{ {
strcpy(json, input); strcpy(json, input);
hashTable = parser.parseHashTable(json); hashTable = parser.parseHashTable(json);
} }
void parseMustFail() void parseMustFail()
{ {
Assert::IsFalse(hashTable.success()); Assert::IsFalse(hashTable.success());
} }
void parseMustSucceed() void parseMustSucceed()
{ {
Assert::IsTrue(hashTable.success()); Assert::IsTrue(hashTable.success());
} }
void itemMustBe(const char* key, long expected) void itemMustBe(const char* key, long expected)
{ {
Assert::AreEqual(expected, hashTable.getLong(key)); Assert::AreEqual(expected, hashTable.getLong(key));
} }
void itemMustBe(const char* key, bool expected) void itemMustBe(const char* key, bool expected)
{ {
Assert::AreEqual(expected, hashTable.getBool(key)); Assert::AreEqual(expected, hashTable.getBool(key));
} }
void itemMustBe(const char* key, const char* expected) void itemMustBe(const char* key, const char* expected)
{ {
Assert::AreEqual(expected, hashTable.getString(key)); Assert::AreEqual(expected, hashTable.getString(key));
} }
void itemMustNotExist(const char* key) void itemMustNotExist(const char* key)
{ {
Assert::IsFalse(hashTable.containsKey(key)); Assert::IsFalse(hashTable.containsKey(key));
Assert::IsFalse(hashTable.getHashTable(key).success()); Assert::IsFalse(hashTable.getHashTable(key).success());
Assert::IsFalse(hashTable.getArray(key).success()); Assert::IsFalse(hashTable.getArray(key).success());
Assert::IsFalse(hashTable.getBool(key)); Assert::IsFalse(hashTable.getBool(key));
Assert::AreEqual(0.0, hashTable.getDouble(key)); Assert::AreEqual(0.0, hashTable.getDouble(key));
Assert::AreEqual(0L, hashTable.getLong(key)); Assert::AreEqual(0L, hashTable.getLong(key));
Assert::IsNull(hashTable.getString(key)); Assert::IsNull(hashTable.getString(key));
} }
void itemMustBeAnArray(const char* key) void itemMustBeAnArray(const char* key)
{ {
nestedArray = hashTable.getArray(key); nestedArray = hashTable.getArray(key);
Assert::IsTrue(nestedArray.success()); Assert::IsTrue(nestedArray.success());
} }
void arrayLengthMustBe(int expected) void arrayLengthMustBe(int expected)
{ {
Assert::AreEqual(expected, nestedArray.getLength()); Assert::AreEqual(expected, nestedArray.getLength());
} }
void arrayItemMustBe(int index, long expected) void arrayItemMustBe(int index, long expected)
{ {
Assert::AreEqual(expected, nestedArray.getLong(index)); Assert::AreEqual(expected, nestedArray.getLong(index));
} }
}; };
} }

View File

@ -1,107 +1,107 @@
/* /*
* Arduino JSON library * Arduino JSON library
* Benoit Blanchon 2014 - MIT License * Benoit Blanchon 2014 - MIT License
*/ */
#include "CppUnitTest.h" #include "CppUnitTest.h"
#include "JsonParser.h" #include "JsonParser.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace ArduinoJson::Parser; using namespace ArduinoJson::Parser;
namespace ArduinoJsonParserTests namespace ArduinoJsonParserTests
{ {
TEST_CLASS(JsonStringTests) TEST_CLASS(JsonStringTests)
{ {
const char* actual; const char* actual;
char json[256]; char json[256];
JsonParser<32> parser; JsonParser<32> parser;
public: public:
TEST_METHOD(EmptyString) TEST_METHOD(EmptyString)
{ {
whenInputIs(""); whenInputIs("");
outputMustBe(0); outputMustBe(0);
} }
TEST_METHOD(JustOneQuote) TEST_METHOD(JustOneQuote)
{ {
whenInputIs("\""); whenInputIs("\"");
outputMustBe(0); outputMustBe(0);
} }
TEST_METHOD(SimpleString) TEST_METHOD(SimpleString)
{ {
whenInputIs("\"Hi!\""); whenInputIs("\"Hi!\"");
outputMustBe("Hi!"); outputMustBe("Hi!");
} }
TEST_METHOD(EscapedQuote) TEST_METHOD(EscapedQuote)
{ {
whenInputIs("\"12\\\"34\""); // ie 12\"34 whenInputIs("\"12\\\"34\""); // ie 12\"34
outputMustBe("12\"34"); outputMustBe("12\"34");
} }
TEST_METHOD(EscapedReverseSolidus) TEST_METHOD(EscapedReverseSolidus)
{ {
whenInputIs("\"12\\\\34\""); // ie 12\\34 whenInputIs("\"12\\\\34\""); // ie 12\\34
outputMustBe("12\\34"); outputMustBe("12\\34");
} }
TEST_METHOD(EscapedSolidus) TEST_METHOD(EscapedSolidus)
{ {
whenInputIs("\"12\\/34\""); whenInputIs("\"12\\/34\"");
outputMustBe("12/34"); outputMustBe("12/34");
} }
TEST_METHOD(EscapedBackspace) TEST_METHOD(EscapedBackspace)
{ {
whenInputIs("\"12\\b34\""); whenInputIs("\"12\\b34\"");
outputMustBe("12\b34"); outputMustBe("12\b34");
} }
TEST_METHOD(EscapedFormfeed) TEST_METHOD(EscapedFormfeed)
{ {
whenInputIs("\"12\\f34\""); whenInputIs("\"12\\f34\"");
outputMustBe("12\f34"); outputMustBe("12\f34");
} }
TEST_METHOD(EscapedNewline) TEST_METHOD(EscapedNewline)
{ {
whenInputIs("\"12\\n34\""); whenInputIs("\"12\\n34\"");
outputMustBe("12\n34"); outputMustBe("12\n34");
} }
TEST_METHOD(EscapedCarriageReturn) TEST_METHOD(EscapedCarriageReturn)
{ {
whenInputIs("\"12\\r34\""); whenInputIs("\"12\\r34\"");
outputMustBe("12\r34"); outputMustBe("12\r34");
} }
TEST_METHOD(EscapedTab) TEST_METHOD(EscapedTab)
{ {
whenInputIs("\"12\\t34\""); whenInputIs("\"12\\t34\"");
outputMustBe("12\t34"); outputMustBe("12\t34");
} }
TEST_METHOD(AllEscapedCharsTogether) TEST_METHOD(AllEscapedCharsTogether)
{ {
whenInputIs("\"1\\\"2\\\\3\\/4\\b5\\f6\\n7\\r8\\t9\""); whenInputIs("\"1\\\"2\\\\3\\/4\\b5\\f6\\n7\\r8\\t9\"");
outputMustBe("1\"2\\3/4\b5\f6\n7\r8\t9"); outputMustBe("1\"2\\3/4\b5\f6\n7\r8\t9");
} }
private: private:
void whenInputIs(const char* input) void whenInputIs(const char* input)
{ {
strcpy(json, input); strcpy(json, input);
actual = parser.parse(json); actual = parser.parse(json);
} }
void outputMustBe(const char* expected) void outputMustBe(const char* expected)
{ {
Assert::AreEqual(expected, actual); Assert::AreEqual(expected, actual);
} }
}; };
} }

View File

@ -1,25 +1,25 @@
#include "stdafx.h" #include "stdafx.h"
#include "CppUnitTest.h" #include "CppUnitTest.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace ArduinoJsonParserTests namespace ArduinoJsonParserTests
{ {
TEST_CLASS(TestHashGenerator) TEST_CLASS(TestHashGenerator)
{ {
public: public:
TEST_METHOD(TestMethod1) TEST_METHOD(TestMethod1)
{ {
JsonArray<5> arr; JsonArray<5> arr;
arr.Add(1); arr.Add(1);
arr.Add("Hi!"); arr.Add("Hi!");
JsonHashTable<4> hash; JsonHashTable<4> hash;
hash.Add("key1", 1); hash.Add("key1", 1);
hash.Add("key2", "Hello!"); hash.Add("key2", "Hello!");
hash.Add("key3", arr); hash.Add("key3", arr);
} }
}; };
} }