| 1 | // Copyright 2024 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "Common/JsonUtil.h" |
| 5 | |
| 6 | #include <fstream> |
| 7 | |
| 8 | #include "Common/FileUtil.h" |
| 9 | |
| 10 | picojson::object ToJsonObject(const Common::Vec3& vec) |
| 11 | { |
| 12 | picojson::object obj; |
| 13 | obj.emplace("x", vec.x); |
| 14 | obj.emplace("y", vec.y); |
| 15 | obj.emplace("z", vec.z); |
| 16 | return obj; |
| 17 | } |
| 18 | |
| 19 | void FromJson(const picojson::object& obj, Common::Vec3& vec) |
| 20 | { |
| 21 | vec.x = ReadNumericFromJson<float>(obj, "x").value_or(0.0f); |
| 22 | vec.y = ReadNumericFromJson<float>(obj, "y").value_or(0.0f); |
| 23 | vec.z = ReadNumericFromJson<float>(obj, "z").value_or(0.0f); |
| 24 | } |
| 25 | |
| 26 | std::optional<std::string> ReadStringFromJson(const picojson::object& obj, const std::string& key) |
| 27 | { |
| 28 | const auto it = obj.find(key); |
| 29 | if (it == obj.end()) |
| 30 | return std::nullopt; |
| 31 | if (!it->second.is<std::string>()) |
| 32 | return std::nullopt; |
| 33 | return it->second.to_str(); |
| 34 | } |
| 35 | |
| 36 | std::optional<bool> ReadBoolFromJson(const picojson::object& obj, const std::string& key) |
| 37 | { |
| 38 | const auto it = obj.find(key); |
| 39 | if (it == obj.end()) |
| 40 | return std::nullopt; |
| 41 | if (!it->second.is<bool>()) |
| 42 | return std::nullopt; |
| 43 | return it->second.get<bool>(); |
| 44 | } |
| 45 | |
| 46 | bool JsonToFile(const std::string& filename, const picojson::value& root, bool prettify) |
| 47 | { |
| 48 | std::ofstream json_stream; |
| 49 | File::OpenFStream(json_stream, filename, std::ios_base::out); |
| 50 | if (!json_stream.is_open()) |
| 51 | { |
| 52 | return false; |
| 53 | } |
| 54 | json_stream << root.serialize(prettify); |
| 55 | return true; |
| 56 | } |
| 57 | |
| 58 | bool JsonFromFile(const std::string& filename, picojson::value* root, std::string* error) |
| 59 | { |
| 60 | std::string json_data; |
| 61 | if (!File::ReadFileToString(filename, json_data)) |
| 62 | { |
| 63 | return false; |
| 64 | } |
| 65 | |
| 66 | *error = picojson::parse(*root, json_data); |
| 67 | return error->empty(); |
| 68 | } |