Test serialization of an object with strings

This commit is contained in:
Benoit Blanchon
2014-09-30 16:59:44 +02:00
parent 3243f2dc58
commit 9f85368cce
6 changed files with 215 additions and 4 deletions

45
srcs/EscapedString.cpp Normal file
View File

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

20
srcs/EscapedString.h Normal file
View File

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

View File

@ -2,6 +2,7 @@
#include <string.h> // for strcmp
#include "EscapedString.h"
#include "JsonBuffer.h"
#include "JsonValue.h"
#include "JsonNode.h"
@ -75,5 +76,28 @@ size_t JsonObject::printTo(char* buffer, size_t bufferSize) const
size_t JsonObject::printTo(Print& p) const
{
return p.print("{}");
size_t n = 0;
n += p.write('{');
JsonNode* firstChild = _node->content.asObject.child;
for (JsonNode* child = firstChild; child; child = child->next)
{
const char* childKey = child->content.asKey.key;
const char* childValue = child->content.asKey.value->content.asString;
n += EscapedString::printTo(childKey, p);
n += p.write(':');
n += EscapedString::printTo(childValue, p);
if (child->next)
{
n += p.write(',');
}
}
n += p.write('}');
return n;
}

View File

@ -67,6 +67,7 @@
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="EscapedString.h" />
<ClInclude Include="JsonBuffer.h" />
<ClInclude Include="JsonNode.h" />
<ClInclude Include="JsonObject.h" />
@ -77,6 +78,7 @@
<ClInclude Include="StringBuilder.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="EscapedString.cpp" />
<ClCompile Include="JsonBuffer.cpp" />
<ClCompile Include="JsonObject.cpp" />
<ClCompile Include="JsonValue.cpp" />

View File

@ -39,6 +39,9 @@
<ClInclude Include="Printable.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="EscapedString.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="JsonObject.cpp">
@ -56,5 +59,8 @@
<ClCompile Include="Print.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="EscapedString.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>