AK: JSON, Escape spacial character in string serialization

This commit is contained in:
Hüseyin ASLITÜRK 2020-05-31 16:02:40 +03:00 committed by Andreas Kling
parent 0b74ea3d6a
commit 8e9776165f
2 changed files with 47 additions and 11 deletions

View file

@ -31,6 +31,7 @@
#include <AK/JsonObjectSerializer.h>
#include <AK/JsonValue.h>
#include <AK/String.h>
#include <AK/StringImpl.h>
namespace AK {
@ -136,9 +137,36 @@ template<typename Builder>
inline void JsonValue::serialize(Builder& builder) const
{
switch (m_type) {
case Type::String:
builder.appendf("\"%s\"", m_value.as_string->characters());
break;
case Type::String: {
auto size = m_value.as_string->length();
builder.append("\"");
for (size_t i = 0; i < size; i++) {
char ch = m_value.as_string->characters()[i];
switch (ch) {
case '\e':
builder.append("\\u001B");
break;
case '\b':
builder.append("\\b");
break;
case '\n':
builder.append("\\n");
break;
case '\t':
builder.append("\\t");
break;
case '\"':
builder.append("\\\"");
break;
case '\\':
builder.append("\\\\");
break;
default:
builder.appendf("%c", ch);
}
}
builder.append("\"");
} break;
case Type::Array:
m_value.as_array->serialize(builder);
break;

View file

@ -116,14 +116,22 @@ String JsonParser::consume_quoted_string()
case 'f':
buffer.append('\f');
break;
case 'u':
consume();
consume();
consume();
consume();
// FIXME: This is obviously not correct, but we don't have non-ASCII support so meh.
buffer.append('?');
break;
case 'u': {
StringBuilder sb;
sb.append(consume());
sb.append(consume());
sb.append(consume());
sb.append(consume());
bool ok;
u32 codepoint = AK::StringUtils::convert_to_uint_from_hex(sb.to_string(), ok);
if (ok && codepoint < 128) {
buffer.append((char)codepoint);
} else {
// FIXME: This is obviously not correct, but we don't have non-ASCII support so meh.
buffer.append('?');
}
} break;
default:
buffer.append(escaped_ch);
break;