json.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. /**
  2. * \file json.h
  3. */
  4. #include <QDebug>
  5. #include "json.h"
  6. static QString sanitizeString(QString str)
  7. {
  8. str.replace(QLatin1String("\\"), QLatin1String("\\\\"));
  9. str.replace(QLatin1String("\""), QLatin1String("\\\""));
  10. str.replace(QLatin1String("\b"), QLatin1String("\\b"));
  11. str.replace(QLatin1String("\f"), QLatin1String("\\f"));
  12. str.replace(QLatin1String("\n"), QLatin1String("\\n"));
  13. str.replace(QLatin1String("\r"), QLatin1String("\\r"));
  14. str.replace(QLatin1String("\t"), QLatin1String("\\t"));
  15. return QString(QLatin1String("\"%1\"")).arg(str);
  16. }
  17. static QByteArray join(const QList<QByteArray> &list, const QByteArray &sep)
  18. {
  19. QByteArray res;
  20. foreach(const QByteArray &i, list)
  21. {
  22. if(!res.isEmpty())
  23. {
  24. res += sep;
  25. }
  26. res += i;
  27. }
  28. return res;
  29. }
  30. /**
  31. * parse
  32. */
  33. QVariant Json::parse(const QString &json)
  34. {
  35. bool success = true;
  36. return Json::parse(json, success);
  37. }
  38. /**
  39. * parse
  40. */
  41. QVariant Json::parse(const QString &json, bool &success)
  42. {
  43. success = true;
  44. //Return an empty QVariant if the JSON data is either null or empty
  45. if(!json.isNull() || !json.isEmpty())
  46. {
  47. QString data = json;
  48. //We'll start from index 0
  49. int index = 0;
  50. //Parse the first value
  51. QVariant value = Json::parseValue(data, index, success);
  52. //Return the parsed value
  53. return value;
  54. }
  55. else
  56. {
  57. //Return the empty QVariant
  58. return QVariant();
  59. }
  60. }
  61. QByteArray Json::serialize(const QVariant &data)
  62. {
  63. bool success = true;
  64. return Json::serialize(data, success);
  65. }
  66. QByteArray Json::serialize(const QVariant &data, bool &success)
  67. {
  68. QByteArray str;
  69. success = true;
  70. if(!data.isValid()) // invalid or null?
  71. {
  72. str = "null";
  73. }
  74. else if(data.type() == QVariant::List) // variant is a list?
  75. {
  76. QList<QByteArray> values;
  77. const QVariantList list = data.toList();
  78. foreach(const QVariant& v, list)
  79. {
  80. QByteArray serializedValue = serialize(v);
  81. if(serializedValue.isNull())
  82. {
  83. success = false;
  84. break;
  85. }
  86. values << serializedValue;
  87. }
  88. str = "[ " + join( values, ", " ) + " ]";
  89. }
  90. else if(data.type() == QVariant::Map) // variant is a map?
  91. {
  92. const QVariantMap vmap = data.toMap();
  93. QMapIterator<QString, QVariant> it( vmap );
  94. str = "{ ";
  95. QList<QByteArray> pairs;
  96. while(it.hasNext())
  97. {
  98. it.next();
  99. QByteArray serializedValue = serialize(it.value());
  100. if(serializedValue.isNull())
  101. {
  102. success = false;
  103. break;
  104. }
  105. pairs << sanitizeString(it.key()).toUtf8() + " : " + serializedValue;
  106. }
  107. str += join(pairs, ", ");
  108. str += " }";
  109. }
  110. else if((data.type() == QVariant::String) || (data.type() == QVariant::ByteArray)) // a string or a byte array?
  111. {
  112. str = sanitizeString(data.toString()).toUtf8();
  113. }
  114. else if(data.type() == QVariant::Double) // double?
  115. {
  116. str = QByteArray::number(data.toDouble());
  117. if(!str.contains(".") && ! str.contains("e"))
  118. {
  119. str += ".0";
  120. }
  121. }
  122. else if (data.type() == QVariant::Bool) // boolean value?
  123. {
  124. str = data.toBool() ? "true" : "false";
  125. }
  126. else if (data.type() == QVariant::ULongLong) // large unsigned number?
  127. {
  128. str = QByteArray::number(data.value<qulonglong>());
  129. }
  130. else if ( data.canConvert<qlonglong>() ) // any signed number?
  131. {
  132. str = QByteArray::number(data.value<qlonglong>());
  133. }
  134. else if (data.canConvert<QString>()) // can value be converted to string?
  135. {
  136. // this will catch QDate, QDateTime, QUrl, ...
  137. str = sanitizeString(data.toString()).toUtf8();
  138. }
  139. else
  140. {
  141. success = false;
  142. }
  143. if (success)
  144. {
  145. return str;
  146. }
  147. else
  148. {
  149. return QByteArray();
  150. }
  151. }
  152. /**
  153. * parseValue
  154. */
  155. QVariant Json::parseValue(const QString &json, int &index, bool &success)
  156. {
  157. //Determine what kind of data we should parse by
  158. //checking out the upcoming token
  159. switch(Json::lookAhead(json, index))
  160. {
  161. case JsonTokenString:
  162. return Json::parseString(json, index, success);
  163. case JsonTokenNumber:
  164. return Json::parseNumber(json, index);
  165. case JsonTokenCurlyOpen:
  166. return Json::parseObject(json, index, success);
  167. case JsonTokenSquaredOpen:
  168. return Json::parseArray(json, index, success);
  169. case JsonTokenTrue:
  170. Json::nextToken(json, index);
  171. return QVariant(true);
  172. case JsonTokenFalse:
  173. Json::nextToken(json, index);
  174. return QVariant(false);
  175. case JsonTokenNull:
  176. Json::nextToken(json, index);
  177. return QVariant();
  178. case JsonTokenNone:
  179. break;
  180. }
  181. //If there were no tokens, flag the failure and return an empty QVariant
  182. success = false;
  183. return QVariant();
  184. }
  185. /**
  186. * parseObject
  187. */
  188. QVariant Json::parseObject(const QString &json, int &index, bool &success)
  189. {
  190. QVariantMap map;
  191. int token;
  192. //Get rid of the whitespace and increment index
  193. Json::nextToken(json, index);
  194. //Loop through all of the key/value pairs of the object
  195. bool done = false;
  196. while(!done)
  197. {
  198. //Get the upcoming token
  199. token = Json::lookAhead(json, index);
  200. if(token == JsonTokenNone)
  201. {
  202. success = false;
  203. return QVariantMap();
  204. }
  205. else if(token == JsonTokenComma)
  206. {
  207. Json::nextToken(json, index);
  208. }
  209. else if(token == JsonTokenCurlyClose)
  210. {
  211. Json::nextToken(json, index);
  212. return map;
  213. }
  214. else
  215. {
  216. //Parse the key/value pair's name
  217. QString name = Json::parseString(json, index, success).toString();
  218. if(!success)
  219. {
  220. return QVariantMap();
  221. }
  222. //Get the next token
  223. token = Json::nextToken(json, index);
  224. //If the next token is not a colon, flag the failure
  225. //return an empty QVariant
  226. if(token != JsonTokenColon)
  227. {
  228. success = false;
  229. return QVariant(QVariantMap());
  230. }
  231. //Parse the key/value pair's value
  232. QVariant value = Json::parseValue(json, index, success);
  233. if(!success)
  234. {
  235. return QVariantMap();
  236. }
  237. //Assign the value to the key in the map
  238. map[name] = value;
  239. }
  240. }
  241. //Return the map successfully
  242. return QVariant(map);
  243. }
  244. /**
  245. * parseArray
  246. */
  247. QVariant Json::parseArray(const QString &json, int &index, bool &success)
  248. {
  249. QVariantList list;
  250. Json::nextToken(json, index);
  251. bool done = false;
  252. while(!done)
  253. {
  254. int token = Json::lookAhead(json, index);
  255. if(token == JsonTokenNone)
  256. {
  257. success = false;
  258. return QVariantList();
  259. }
  260. else if(token == JsonTokenComma)
  261. {
  262. Json::nextToken(json, index);
  263. }
  264. else if(token == JsonTokenSquaredClose)
  265. {
  266. Json::nextToken(json, index);
  267. break;
  268. }
  269. else
  270. {
  271. QVariant value = Json::parseValue(json, index, success);
  272. if(!success)
  273. {
  274. return QVariantList();
  275. }
  276. list.push_back(value);
  277. }
  278. }
  279. return QVariant(list);
  280. }
  281. /**
  282. * parseString
  283. */
  284. QVariant Json::parseString(const QString &json, int &index, bool &success)
  285. {
  286. QString s;
  287. QChar c;
  288. Json::eatWhitespace(json, index);
  289. c = json[index++];
  290. bool complete = false;
  291. while(!complete)
  292. {
  293. if(index == json.size())
  294. {
  295. break;
  296. }
  297. c = json[index++];
  298. if(c == '\"')
  299. {
  300. complete = true;
  301. break;
  302. }
  303. else if(c == '\\')
  304. {
  305. if(index == json.size())
  306. {
  307. break;
  308. }
  309. c = json[index++];
  310. if(c == '\"')
  311. {
  312. s.append('\"');
  313. }
  314. else if(c == '\\')
  315. {
  316. s.append('\\');
  317. }
  318. else if(c == '/')
  319. {
  320. s.append('/');
  321. }
  322. else if(c == 'b')
  323. {
  324. s.append('\b');
  325. }
  326. else if(c == 'f')
  327. {
  328. s.append('\f');
  329. }
  330. else if(c == 'n')
  331. {
  332. s.append('\n');
  333. }
  334. else if(c == 'r')
  335. {
  336. s.append('\r');
  337. }
  338. else if(c == 't')
  339. {
  340. s.append('\t');
  341. }
  342. else if(c == 'u')
  343. {
  344. int remainingLength = json.size() - index;
  345. if(remainingLength >= 4)
  346. {
  347. QString unicodeStr = json.mid(index, 4);
  348. int symbol = unicodeStr.toInt(0, 16);
  349. s.append(QChar(symbol));
  350. index += 4;
  351. }
  352. else
  353. {
  354. break;
  355. }
  356. }
  357. }
  358. else
  359. {
  360. s.append(c);
  361. }
  362. }
  363. if(!complete)
  364. {
  365. success = false;
  366. return QVariant();
  367. }
  368. return QVariant(s);
  369. }
  370. /**
  371. * parseNumber
  372. */
  373. QVariant Json::parseNumber(const QString &json, int &index)
  374. {
  375. Json::eatWhitespace(json, index);
  376. int lastIndex = Json::lastIndexOfNumber(json, index);
  377. int charLength = (lastIndex - index) + 1;
  378. QString numberStr;
  379. numberStr = json.mid(index, charLength);
  380. index = lastIndex + 1;
  381. return QVariant(numberStr.toDouble(NULL));
  382. }
  383. /**
  384. * lastIndexOfNumber
  385. */
  386. int Json::lastIndexOfNumber(const QString &json, int index)
  387. {
  388. int lastIndex;
  389. for(lastIndex = index; lastIndex < json.size(); lastIndex++)
  390. {
  391. if(QString("0123456789+-.eE").indexOf(json[lastIndex]) == -1)
  392. {
  393. break;
  394. }
  395. }
  396. return lastIndex -1;
  397. }
  398. /**
  399. * eatWhitespace
  400. */
  401. void Json::eatWhitespace(const QString &json, int &index)
  402. {
  403. for(; index < json.size(); index++)
  404. {
  405. if(QString(" \t\n\r").indexOf(json[index]) == -1)
  406. {
  407. break;
  408. }
  409. }
  410. }
  411. /**
  412. * lookAhead
  413. */
  414. int Json::lookAhead(const QString &json, int index)
  415. {
  416. int saveIndex = index;
  417. return Json::nextToken(json, saveIndex);
  418. }
  419. /**
  420. * nextToken
  421. */
  422. int Json::nextToken(const QString &json, int &index)
  423. {
  424. Json::eatWhitespace(json, index);
  425. if(index == json.size())
  426. {
  427. return JsonTokenNone;
  428. }
  429. QChar c = json[index];
  430. index++;
  431. switch(c.toAscii())
  432. {
  433. case '{': return JsonTokenCurlyOpen;
  434. case '}': return JsonTokenCurlyClose;
  435. case '[': return JsonTokenSquaredOpen;
  436. case ']': return JsonTokenSquaredClose;
  437. case ',': return JsonTokenComma;
  438. case '"': return JsonTokenString;
  439. case '0': case '1': case '2': case '3': case '4':
  440. case '5': case '6': case '7': case '8': case '9':
  441. case '-': return JsonTokenNumber;
  442. case ':': return JsonTokenColon;
  443. }
  444. index--;
  445. int remainingLength = json.size() - index;
  446. //True
  447. if(remainingLength >= 4)
  448. {
  449. if (json[index] == 't' && json[index + 1] == 'r' &&
  450. json[index + 2] == 'u' && json[index + 3] == 'e')
  451. {
  452. index += 4;
  453. return JsonTokenTrue;
  454. }
  455. }
  456. //False
  457. if (remainingLength >= 5)
  458. {
  459. if (json[index] == 'f' && json[index + 1] == 'a' &&
  460. json[index + 2] == 'l' && json[index + 3] == 's' &&
  461. json[index + 4] == 'e')
  462. {
  463. index += 5;
  464. return JsonTokenFalse;
  465. }
  466. }
  467. //Null
  468. if (remainingLength >= 4)
  469. {
  470. if (json[index] == 'n' && json[index + 1] == 'u' &&
  471. json[index + 2] == 'l' && json[index + 3] == 'l')
  472. {
  473. index += 4;
  474. return JsonTokenNull;
  475. }
  476. }
  477. return JsonTokenNone;
  478. }