File: JsonUtil.cpp

package info (click to toggle)
dolphin-emu 2512%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 76,328 kB
  • sloc: cpp: 499,023; ansic: 119,674; python: 6,547; sh: 2,338; makefile: 1,093; asm: 726; pascal: 257; javascript: 183; perl: 97; objc: 75; xml: 30
file content (68 lines) | stat: -rw-r--r-- 1,715 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright 2024 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "Common/JsonUtil.h"

#include <fstream>

#include "Common/FileUtil.h"

picojson::object ToJsonObject(const Common::Vec3& vec)
{
  picojson::object obj;
  obj.emplace("x", vec.x);
  obj.emplace("y", vec.y);
  obj.emplace("z", vec.z);
  return obj;
}

void FromJson(const picojson::object& obj, Common::Vec3& vec)
{
  vec.x = ReadNumericFromJson<float>(obj, "x").value_or(0.0f);
  vec.y = ReadNumericFromJson<float>(obj, "y").value_or(0.0f);
  vec.z = ReadNumericFromJson<float>(obj, "z").value_or(0.0f);
}

std::optional<std::string> ReadStringFromJson(const picojson::object& obj, const std::string& key)
{
  const auto it = obj.find(key);
  if (it == obj.end())
    return std::nullopt;
  if (!it->second.is<std::string>())
    return std::nullopt;
  return it->second.to_str();
}

std::optional<bool> ReadBoolFromJson(const picojson::object& obj, const std::string& key)
{
  const auto it = obj.find(key);
  if (it == obj.end())
    return std::nullopt;
  if (!it->second.is<bool>())
    return std::nullopt;
  return it->second.get<bool>();
}

bool JsonToFile(const std::string& filename, const picojson::value& root, bool prettify)
{
  std::ofstream json_stream;
  File::OpenFStream(json_stream, filename, std::ios_base::out);
  if (!json_stream.is_open())
  {
    return false;
  }
  json_stream << root.serialize(prettify);
  return true;
}

bool JsonFromFile(const std::string& filename, picojson::value* root, std::string* error)
{
  std::string json_data;
  if (!File::ReadFileToString(filename, json_data))
  {
    return false;
  }

  *error = picojson::parse(*root, json_data);
  return error->empty();
}