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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
|
/*
This file is part of Warzone 2100.
Copyright (C) 1999-2004 Eidos Interactive
Copyright (C) 2005-2021 Warzone 2100 Project
Warzone 2100 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; either version 2 of the License, or
(at your option) any later version.
Warzone 2100 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Warzone 2100; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/** @file wzconfig.cpp
* Ini related functions.
*/
// Get platform defines before checking for them.
#include "wzconfig.h"
#include <physfs.h>
#include "file.h"
#include <sstream>
#include <limits>
#include "physfs_ext.h"
WzConfig::~WzConfig()
{
if (mWarning == ReadAndWrite)
{
ASSERT(mObjStack.empty(), "Some json groups have not been closed, stack size %zu.", mObjStack.size());
std::ostringstream stream;
stream << mRoot.dump(4) << std::endl;
std::string jsonString = stream.str();
#if SIZE_MAX >= UDWORD_MAX
ASSERT(jsonString.size() <= static_cast<size_t>(std::numeric_limits<UDWORD>::max()), "jsonString.size (%zu) exceeds UDWORD::max", jsonString.size());
#endif
saveFile(mFilename.toUtf8().c_str(), jsonString.c_str(), static_cast<UDWORD>(jsonString.size()));
}
debug(LOG_SAVE, "%s %s", mWarning == ReadAndWrite? "Saving" : "Closing", mFilename.toUtf8().c_str());
}
static nlohmann::json jsonMerge(nlohmann::json original, const nlohmann::json& override)
{
for (auto it_override = override.begin(); it_override != override.end(); ++it_override)
{
auto key = it_override.key();
auto it_original = original.find(key);
if (it_override.value().is_object() && (it_original != original.end()))
{
original[key] = jsonMerge(it_original.value(), it_override.value());
}
else if (it_override.value().is_null())
{
original.erase(key);
}
else
{
original[key] = it_override.value();
}
}
return original;
}
WzConfig::WzConfig(const WzString &name, WzConfig::warning warning)
: mArray(nlohmann::json::array())
{
UDWORD size = 0;
char *data = nullptr;
mFilename = name;
mStatus = true;
mWarning = warning;
pCurrentObj = &mRoot;
if (!PHYSFS_exists(name.toUtf8().c_str()))
{
if (warning == ReadOnly)
{
mStatus = false;
return;
}
else if (warning == ReadOnlyAndRequired)
{
debug(LOG_FATAL, "Missing required file %s", name.toUtf8().c_str());
abort();
}
else if (warning == ReadAndWrite)
{
return;
}
}
if (!loadFile(name.toUtf8().c_str(), &data, &size))
{
mStatus = false;
debug(LOG_FATAL, "Could not open \"%s\"", name.toUtf8().c_str());
return;
}
ASSERT_OR_RETURN(, data != nullptr, "Null data?");
try {
mRoot = nlohmann::json::parse(data, data + size);
}
catch (const std::exception &e) {
ASSERT(false, "JSON document from %s is invalid: %s", name.toUtf8().c_str(), e.what());
}
catch (...) {
debug(LOG_FATAL, "Unexpected exception parsing JSON %s", name.toUtf8().c_str());
}
pCurrentObj = &mRoot;
ASSERT(!mRoot.is_null(), "JSON document from %s is null", name.toUtf8().c_str());
ASSERT(mRoot.is_object(), "JSON document from %s is not an object. Read: \n%s", name.toUtf8().c_str(), data);
free(data);
WZ_PHYSFS_enumerateFolders("diffs", [&](const char *i) -> bool {
std::string str(std::string("diffs/") + i + std::string("/") + name.toUtf8().c_str());
if (!PHYSFS_exists(str.c_str()))
{
return true; // continue;
}
UDWORD size = 0;
char *data = nullptr;
if (!loadFile(str.c_str(), &data, &size))
{
debug(LOG_FATAL, "jsondiff file \"%s\" could not be opened!", name.toUtf8().c_str());
}
nlohmann::json tmpJson;
try {
tmpJson = nlohmann::json::parse(data, data + size);
}
catch (const std::exception &e) {
ASSERT(false, "JSON diff from %s is invalid: %s", name.toUtf8().c_str(), e.what());
}
catch (...) {
debug(LOG_FATAL, "Unexpected exception parsing JSON diff from %s", name.toUtf8().c_str());
}
ASSERT(!tmpJson.is_null(), "JSON diff from %s is null", name.toUtf8().c_str());
ASSERT(tmpJson.is_object(), "JSON diff from %s is not an object. Read: \n%s", name.toUtf8().c_str(), data);
mRoot = jsonMerge(mRoot, tmpJson);
free(data);
debug(LOG_INFO, "jsondiff \"%s\" loaded and merged", str.c_str());
return true; // continue
});
debug(LOG_SAVE, "Opening %s", name.toUtf8().c_str());
pCurrentObj = &mRoot;
}
bool WzConfig::isAtDocumentRoot() const
{
return pCurrentObj == &mRoot;
}
std::string WzConfig::compactStringRepresentation(const bool ensure_ascii) const
{
// Use the most compact representation of the JSON
return mRoot.dump(-1, ' ', ensure_ascii);
}
std::vector<WzString> WzConfig::childGroups() const
{
ASSERT_OR_RETURN({}, pCurrentObj != nullptr, "current object is nullptr");
ASSERT_OR_RETURN({}, pCurrentObj->is_object(), "current pointer is not an object");
std::vector<WzString> keys;
for (auto it = pCurrentObj->begin(); it != pCurrentObj->end(); ++it)
{
if (it.value().is_object())
{
keys.push_back(WzString::fromUtf8(it.key().c_str()));
}
}
return keys;
}
std::vector<WzString> WzConfig::childKeys() const
{
ASSERT_OR_RETURN({}, pCurrentObj != nullptr, "current object is nullptr");
ASSERT_OR_RETURN({}, pCurrentObj->is_object(), "current pointer is not an object");
std::vector<WzString> keys;
for (auto it = pCurrentObj->begin(); it != pCurrentObj->end(); ++it)
{
keys.push_back(WzString::fromUtf8(it.key().c_str()));
}
return keys;
}
bool WzConfig::contains(const WzString &key) const
{
return pCurrentObj->find(key.toUtf8()) != pCurrentObj->end();
}
json_variant WzConfig::value(const WzString &key, const json_variant &defaultValue) const
{
return json_getValue(*pCurrentObj, key, defaultValue);
}
nlohmann::json WzConfig::json(const WzString &key, const nlohmann::json &defaultValue) const
{
auto it = pCurrentObj->find(key.toUtf8());
if (it == pCurrentObj->end())
{
return defaultValue;
}
else
{
return it.value();
}
}
nlohmann::json& WzConfig::currentJsonValue() const
{
ASSERT(pCurrentObj, "pCurrentObj is null");
return *pCurrentObj;
}
WzString WzConfig::string(const WzString &key, const WzString &defaultValue) const
{
auto it = pCurrentObj->find(key.toUtf8());
if (it == pCurrentObj->end())
{
return defaultValue;
}
else
{
// Use json_variant to support conversion from other value types to string
bool ok = false;
WzString stringValue = json_variant(it.value()).toWzString(&ok);
if (!ok)
{
ASSERT(false, "Failed to convert value of key \"%s\" to string", key.toUtf8().c_str());
return defaultValue;
}
return stringValue;
}
}
void WzConfig::setVector3f(const WzString &name, const Vector3f &v)
{
(*pCurrentObj)[name.toUtf8()] = nlohmann::json::array({ v.x, v.y, v.z });
}
Vector3f WzConfig::vector3f(const WzString &name)
{
Vector3f r(0.0, 0.0, 0.0);
auto it = pCurrentObj->find(name.toUtf8());
if (it == pCurrentObj->end())
{
return r;
}
auto v = it.value();
ASSERT(v.size() == 3, "%s: Bad list of %s", mFilename.toUtf8().c_str(), name.toUtf8().c_str());
try {
r.x = v[0].get<float>();
r.y = v[1].get<float>();
r.z = v[2].get<float>();
}
catch (const std::exception &e) {
ASSERT(false, "%s: Bad list of %s; exception: %s", mFilename.toUtf8().c_str(), name.toUtf8().c_str(), e.what());
}
catch (...) {
debug(LOG_FATAL, "Unexpected exception encountered in vector3f");
}
return r;
}
void WzConfig::setVector3i(const WzString &name, const Vector3i &v)
{
(*pCurrentObj)[name.toUtf8()] = nlohmann::json::array({ v.x, v.y, v.z });
}
Vector3i WzConfig::vector3i(const WzString &name)
{
Vector3i r(0, 0, 0);
auto it = pCurrentObj->find(name.toUtf8());
if (it == pCurrentObj->end())
{
return r;
}
auto v = it.value();
ASSERT(v.size() == 3, "%s: Bad list of %s", mFilename.toUtf8().c_str(), name.toUtf8().c_str());
try {
r.x = v[0].get<int>();
r.y = v[1].get<int>();
r.z = v[2].get<int>();
}
catch (const std::exception &e) {
ASSERT(false, "%s: Bad list of %s; exception: %s", mFilename.toUtf8().c_str(), name.toUtf8().c_str(), e.what());
}
catch (...) {
debug(LOG_FATAL, "Unexpected exception encountered in vector3f");
}
return r;
}
void WzConfig::setVector2i(const WzString &name, const Vector2i &v)
{
(*pCurrentObj)[name.toUtf8()] = nlohmann::json::array({ v.x, v.y });
}
Vector2i WzConfig::vector2i(const WzString &name)
{
Vector2i r(0, 0);
auto it = pCurrentObj->find(name.toUtf8());
if (it == pCurrentObj->end())
{
return r;
}
auto v = it.value();
ASSERT(v.size() == 2, "Bad list of %s", name.toUtf8().c_str());
try {
r.x = v[0].get<int>();
r.y = v[1].get<int>();
}
catch (const std::exception &e) {
ASSERT(false, "%s: Bad list of %s; exception: %s", mFilename.toUtf8().c_str(), name.toUtf8().c_str(), e.what());
}
catch (...) {
debug(LOG_FATAL, "Unexpected exception encountered in vector3f");
}
return r;
}
bool WzConfig::beginGroup(const WzString &prefix)
{
mObjNameStack.push_back(mName);
mObjStack.push_back(pCurrentObj);
mName = prefix;
if (mWarning == ReadAndWrite)
{
mNewObjStack.push_back(nlohmann::json::object());
pCurrentObj = &mNewObjStack.back();
}
else
{
auto it = pCurrentObj->find(prefix.toUtf8());
// Check if mObj contains the prefix
if (it == pCurrentObj->end()) // handled in this way for backwards compatibility
{
mNewObjStack.push_back(nlohmann::json::object());
pCurrentObj = &mNewObjStack.back();
return false;
}
ASSERT(it.value().is_object(), "%s: beginGroup() on non-object key \"%s\"", mFilename.toUtf8().c_str(), prefix.toUtf8().c_str());
pCurrentObj = &it.value();
}
return true;
}
void WzConfig::endGroup()
{
ASSERT(!mObjStack.empty(), "An endGroup() too much!");
if (mWarning == ReadAndWrite)
{
nlohmann::json *pLatestObj = pCurrentObj;
pCurrentObj = mObjStack.back();
mObjStack.pop_back();
if (!mNewObjStack.empty() && &mNewObjStack.back() == pLatestObj)
{
(*pCurrentObj)[mName.toUtf8()] = *pLatestObj;
mNewObjStack.pop_back();
}
else
{
// this object is not a "new" object, and so is already source from the current obj
debug(LOG_INFO, "Got it");
}
mName = mObjNameStack.back();
mObjNameStack.pop_back();
}
else
{
if (!mNewObjStack.empty() && &mNewObjStack.back() == pCurrentObj)
{
mNewObjStack.pop_back();
}
mName = mObjNameStack.back();
mObjNameStack.pop_back();
pCurrentObj = mObjStack.back();
mObjStack.pop_back();
}
}
// This function is intended to be paired with endArray().
//
// [Creation Case]:
//
// By calling beginArray with a name, a new array value at the desired key (name) is created in the current object.
// The current object is then set to a **new JSON object**, which can be further manipulated.
//
// Calling nextArrayItem() inserts the current object into the current array, and then sets the current object
// to a new JSON object.
//
// Calling endArray() then finalizes and sets the array value in the (original / parent) object for key "name".
//
// [Read-only Case]:
//
// Similarly, beginArray() let's you traverse the array of objects found at key "name". (With some backwards-compatibility quirks.)
//
// The current object is set to the first object in the array. Subsequent calls to nextArrayItem() will increment which array object
// the current object points to.
//
void WzConfig::beginArray(const WzString &name)
{
ASSERT(mArray.empty(), "beginArray() cannot be nested");
mObjNameStack.push_back(mName);
mObjStack.push_back(pCurrentObj);
mName = name;
if (mWarning == ReadAndWrite)
{
mNewObjStack.push_back(nlohmann::json::object());
pCurrentObj = &mNewObjStack.back();
}
else
{
auto it = pCurrentObj->find(name.toUtf8());
// Check if mObj contains the name
if (it == pCurrentObj->end()) // handled in this way for backwards compatibility
{
return;
}
ASSERT(it.value().is_array(), "%s: beginArray() on non-array key \"%s\"", mFilename.toUtf8().c_str(), name.toUtf8().c_str());
mArray = it.value();
if (mArray.size() == 0)
{
return;
}
ASSERT(mArray.front().is_object(), "%s: beginArray() on non-object array \"%s\"", mFilename.toUtf8().c_str(), name.toUtf8().c_str());
pCurrentObj = &mArray.front();
}
}
void WzConfig::nextArrayItem()
{
if (mWarning == ReadAndWrite)
{
mArray.push_back(*pCurrentObj);
if (!mNewObjStack.empty() && &mNewObjStack.back() == pCurrentObj)
{
mNewObjStack.pop_back();
}
mNewObjStack.push_back(nlohmann::json::object());
pCurrentObj = &mNewObjStack.back();
}
else
{
if (!mArray.empty())
{
mArray.erase(mArray.begin());
if (!mArray.empty())
{
pCurrentObj = &mArray.front();
}
else
{
mNewObjStack.push_back(nlohmann::json::object());
pCurrentObj = &mNewObjStack.back();
}
}
}
}
size_t WzConfig::remainingArrayItems()
{
return mArray.size();
}
void WzConfig::endArray()
{
if (mWarning == ReadAndWrite)
{
if (!pCurrentObj->empty())
{
mArray.push_back(*pCurrentObj);
}
if (!mNewObjStack.empty() && &mNewObjStack.back() == pCurrentObj)
{
mNewObjStack.pop_back();
}
pCurrentObj = mObjStack.back();
mObjStack.pop_back();
if (!mArray.empty())
{
ASSERT(pCurrentObj != nullptr, "pCurrentObj is null");
(*pCurrentObj)[mName.toUtf8()] = mArray;
}
mName = mObjNameStack.back();
mObjNameStack.pop_back();
}
else
{
if (!mNewObjStack.empty() && &mNewObjStack.back() == pCurrentObj)
{
mNewObjStack.pop_back();
}
mName = mObjNameStack.back();
mObjNameStack.pop_back();
pCurrentObj = mObjStack.back();
mObjStack.pop_back();
}
mArray = nlohmann::json::array();
}
void WzConfig::setValue(const WzString &key, const nlohmann::json &&value)
{
ASSERT(pCurrentObj != nullptr, "pCurrentObj is null");
(*pCurrentObj)[key.toUtf8()] = value;
}
void WzConfig::setValue(const WzString &key, const nlohmann::json &value)
{
ASSERT(pCurrentObj != nullptr, "pCurrentObj is null");
(*pCurrentObj)[key.toUtf8()] = value;
}
void WzConfig::set(const WzString &key, const nlohmann::json &value)
{
setValue(key, value);
}
// MARK: json_variant
json_variant::json_variant(int i)
: mObj(i)
{ }
json_variant::json_variant(const char * str)
: mObj(str)
{ }
json_variant::json_variant(const std::string & str)
: mObj(str)
{ }
json_variant::json_variant(const WzString & str)
: mObj(str.toUtf8())
{ }
const nlohmann::json& json_variant::jsonValue() const
{
return mObj;
}
#include <typeinfo>
template<typename TYPE>
static TYPE json_variant_toType(const json_variant& json, bool *ok, TYPE defaultValue)
{
TYPE result = defaultValue;
try {
result = json.jsonValue().get<TYPE>();
if (ok != nullptr)
{
*ok = true;
}
}
catch (const std::exception &e) {
debug(LOG_WARNING, "Failed to convert json_variant to %s because of error: %s", typeid(TYPE).name(), e.what());
if (ok != nullptr)
{
*ok = false;
}
result = defaultValue;
}
catch (...) {
debug(LOG_FATAL, "Unexpected exception encountered: json_variant::toType<%s>", typeid(TYPE).name());
}
return result;
}
int json_variant::toInt(bool *ok /*= nullptr*/) const
{
if (mObj.is_number())
{
return json_variant_toType<int>(*this, ok, 0);
}
else if (mObj.is_boolean())
{
bool result = json_variant_toType<bool>(*this, ok, false);
return (int)result;
}
else if (mObj.is_string())
{
std::string result = json_variant_toType<std::string>(*this, ok, std::string());
try {
return std::stoi(result);
}
catch (const std::exception &e) {
debug(LOG_WARNING, "Failed to convert string '%s' to int because of error: %s", result.c_str(), e.what());
return 0;
}
}
else if (mObj.is_null())
{
return 0;
}
else
{
return 0;
}
}
unsigned int json_variant::toUInt(bool *ok /*= nullptr*/) const
{
if (mObj.is_number())
{
return json_variant_toType<unsigned int>(*this, ok, 0);
}
else if (mObj.is_boolean())
{
bool result = json_variant_toType<bool>(*this, ok, false);
return (unsigned int)result;
}
else if (mObj.is_string())
{
std::string result = json_variant_toType<std::string>(*this, ok, std::string());
try {
unsigned long ulongValue = std::stoul(result);
if (ulongValue > std::numeric_limits<unsigned int>::max())
{
debug(LOG_WARNING, "Failed to convert string '%s' to unsigned int because of error: value is > std::numeric_limits<unsigned int>::max()", result.c_str());
return 0;
}
return (unsigned int)ulongValue;
}
catch (const std::exception &e) {
debug(LOG_WARNING, "Failed to convert string '%s' to unsigned int because of error: %s", result.c_str(), e.what());
return 0;
}
}
else if (mObj.is_null())
{
return 0;
}
else
{
return 0;
}
}
uint64_t json_variant::toUint64(bool *ok /*= nullptr*/) const
{
if (mObj.is_number())
{
return json_variant_toType<uint64_t>(*this, ok, 0);
}
else if (mObj.is_boolean())
{
bool result = json_variant_toType<bool>(*this, ok, false);
return (uint64_t)result;
}
else if (mObj.is_string())
{
std::string result = json_variant_toType<std::string>(*this, ok, std::string());
try {
unsigned long long ulonglongValue = std::stoull(result);
#if ULLONG_MAX > UINT64_MAX
if (ulonglongValue > std::numeric_limits<uint64_t>::max())
{
debug(LOG_WARNING, "Failed to convert string '%s' to uint64_t because of error: value is > std::numeric_limits<uint64_t>::max()", result.c_str());
return 0;
}
#endif
return (uint64_t)ulonglongValue;
}
catch (const std::exception &e) {
debug(LOG_WARNING, "Failed to convert string '%s' to uint64_t because of error: %s", result.c_str(), e.what());
return 0;
}
}
else if (mObj.is_null())
{
return 0;
}
else
{
return 0;
}
}
#include <algorithm>
bool json_variant::toBool() const
{
if (mObj.is_boolean())
{
return json_variant_toType<bool>(*this, nullptr, false);
}
else if (mObj.is_number())
{
double result = json_variant_toType<double>(*this, nullptr, 0);
return result != 0;
}
else if (mObj.is_string())
{
std::string result = json_variant_toType<std::string>(*this, nullptr, std::string());
std::transform(result.begin(), result.end(), result.begin(), [](const std::string::value_type& c) { return std::tolower(c, std::locale::classic()); });
return !result.empty() && result != "0" && result != "false";
}
else
{
debug(LOG_INFO, "Expected a json value that can be converted to a boolean, instead received: %s", mObj.type_name());
return false;
}
}
double json_variant::toDouble(bool *ok /*= nullptr*/) const
{
if (mObj.is_number_float())
{
return json_variant_toType<double>(*this, ok, 0.0);
}
else if (mObj.is_number_unsigned())
{
json::number_unsigned_t intValue = json_variant_toType<json::number_unsigned_t>(*this, ok, 0);
return (double)intValue;
}
else if (mObj.is_number_integer())
{
json::number_integer_t intValue = json_variant_toType<json::number_integer_t>(*this, ok, 0);
return (double)intValue;
}
else if (mObj.is_boolean())
{
return (double)json_variant_toType<bool>(*this, ok, false);
}
else if (mObj.is_string())
{
std::string result = json_variant_toType<std::string>(*this, ok, std::string());
try {
return std::stod(result);
}
catch (const std::exception &e) {
debug(LOG_WARNING, "Failed to convert string '%s' to double because of error: %s", result.c_str(), e.what());
return 0;
}
}
else if (mObj.is_null())
{
return 0;
}
else
{
return 0;
}
}
float json_variant::toFloat(bool *ok /*= nullptr*/) const
{
if (mObj.is_number_float())
{
return json_variant_toType<float>(*this, ok, 0.0);
}
else if (mObj.is_number_unsigned())
{
json::number_unsigned_t intValue = json_variant_toType<json::number_unsigned_t>(*this, ok, 0);
return (float)intValue;
}
else if (mObj.is_number_integer())
{
json::number_integer_t intValue = json_variant_toType<json::number_integer_t>(*this, ok, 0);
return (float)intValue;
}
else if (mObj.is_boolean())
{
return (float)json_variant_toType<bool>(*this, ok, false);
}
else if (mObj.is_string())
{
std::string result = json_variant_toType<std::string>(*this, ok, std::string());
try {
return std::stof(result);
}
catch (const std::exception &e) {
debug(LOG_WARNING, "Failed to convert string '%s' to float because of error: %s", result.c_str(), e.what());
return 0;
}
}
else if (mObj.is_null())
{
return 0;
}
else
{
return 0;
}
}
WzString json_variant::toWzString(bool *ok /*= nullptr*/) const
{
if (mObj.is_string())
{
return json_variant_toType<WzString>(*this, ok, WzString());
}
else if (mObj.is_boolean())
{
bool result = json_variant_toType<bool>(*this, ok, false);
return (result) ? WzString::fromUtf8("true") : WzString::fromUtf8("false");
}
else if (mObj.is_number_unsigned())
{
json::number_unsigned_t intValue = json_variant_toType<json::number_unsigned_t>(*this, ok, 0);
return WzString::number(intValue);
}
else if (mObj.is_number_integer())
{
json::number_integer_t intValue = json_variant_toType<json::number_integer_t>(*this, ok, 0);
return WzString::number(intValue);
}
else if (mObj.is_number_float())
{
json::number_float_t floatValue = json_variant_toType<json::number_float_t>(*this, ok, 0);
return WzString::number(floatValue);
}
else if (mObj.is_null())
{
return WzString();
}
else
{
if (ok != nullptr)
{
*ok = false;
}
return WzString();
}
}
std::vector<WzString> json_variant::toWzStringList() const
{
std::vector<WzString> result;
if (!mObj.is_array())
{
// attempt to convert the non-array to a string, and return as a vector of 1 entry (if the string is non-empty)
WzString selfAsString = toWzString();
if (!selfAsString.isEmpty())
{
result.push_back(selfAsString);
}
return result;
}
WzString str;
bool ok = false;
for (const auto& v : mObj)
{
// Use json_variant to support conversion from other value types to string
str = json_variant(v).toWzString(&ok);
if (!ok)
{
debug(LOG_WARNING, "Encountered a JSON value in the array that cannot be converted to a string (type: %s)", v.type_name());
break;
}
result.push_back(str);
}
return result;
}
// Convenience methods
json_variant json_getValue(const nlohmann::json& json, const WzString &key, const json_variant &defaultValue /*= json_variant()*/)
{
auto it = json.find(key.toUtf8());
if (it == json.end())
{
return defaultValue;
}
else
{
return json_variant(it.value());
}
}
json_variant json_getValue(const nlohmann::json& json, nlohmann::json::size_type idx, const json_variant &defaultValue /*= json_variant()*/)
{
try {
return json_variant(json.at(idx));
}
catch (const std::exception&) {
return defaultValue;
}
catch (...) {
debug(LOG_FATAL, "Encountered unexpected exception in json_getValue");
return defaultValue;
}
}
|