Advertisement
Guest User

json.hpp

a guest
Oct 1st, 2022
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. /*
  2.  * This file is part of OpenTTD.
  3.  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
  4.  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  5.  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
  6.  */
  7.  
  8. #include "3rdparty/json11/json11.hpp"
  9.  
  10. using namespace json11;
  11. using namespace std;
  12.  
  13. /**
  14.  * Parse a JSON file stored in _file_to_saveload.
  15.  * @returns The file parsed as a json11:Json object.
  16.  */
  17. Json ParseJsonFromLoadedFile()
  18. {
  19.     string err; ///< Holds the error message generated by the json11 parser.
  20.  
  21.     /* Load the GeoJSON file as a string initially. We'll parse it soon.. */
  22.     size_t filesize;
  23.     char *text{};
  24.     FILE *handle = FioFOpenFile(_file_to_saveload.name, "rb", GEODATA_DIR, &filesize);
  25.     if (handle == nullptr) return false;
  26.  
  27.     text = ReallocT(text, filesize);
  28.     size_t read = fread(text, 1, filesize, handle);
  29.     fclose(handle);
  30.  
  31.     if (read != filesize) return false;
  32.  
  33.     /* Add a trailing \0 to mark the end of the string */
  34.     text = ReallocT(text, filesize + 1);
  35.     text[filesize] = '\0';
  36.  
  37.     /* The parser doesn't like tabs or various newline characters, so we'll replace them with a space. */
  38.     for (char *p = text; *p != '\0'; p++) {
  39.         if (*p == '\t' || *p == '\r' || *p == '\n' || *p == '\r\n') *p = ' ';
  40.     }
  41.  
  42.     /* Finally time to parse the string. */
  43.     // TODO: Show errors from invalid JSON load to the player.
  44.     return Json::parse(text, err);
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement