3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "serialize.h"
25 // Creates a string encoded in JSON format (almost equivalent to a C string literal)
26 std::string serializeJsonString(const std::string &plain)
28 std::ostringstream os(std::ios::binary);
30 for(size_t i = 0; i < plain.size(); i++)
35 case '"': os<<"\\\""; break;
36 case '\\': os<<"\\\\"; break;
37 case '/': os<<"\\/"; break;
38 case '\b': os<<"\\b"; break;
39 case '\f': os<<"\\f"; break;
40 case '\n': os<<"\\n"; break;
41 case '\r': os<<"\\r"; break;
42 case '\t': os<<"\\t"; break;
45 if(c >= 32 && c <= 126)
51 u32 cnum = (u32) (u8) c;
52 os<<"\\u"<<std::hex<<std::setw(4)<<std::setfill('0')<<cnum;
62 // Reads a string encoded in JSON format
63 std::string deSerializeJsonString(std::istream &is)
65 std::ostringstream os(std::ios::binary);
68 // Parse initial doublequote
71 throw SerializationError("JSON string must start with doublequote");
78 throw SerializationError("JSON string ended prematurely");
87 throw SerializationError("JSON string ended prematurely");
90 default: os<<c2; break;
91 case 'b': os<<'\b'; break;
92 case 'f': os<<'\f'; break;
93 case 'n': os<<'\n'; break;
94 case 'r': os<<'\r'; break;
95 case 't': os<<'\t'; break;
99 is.read(hexdigits, 4);
101 throw SerializationError("JSON string ended prematurely");
103 std::istringstream tmp_is(hexdigits, std::ios::binary);
105 tmp_is >> std::hex >> hexnumber;
106 os<<((char)hexnumber);