Skip to content

Commit

Permalink
Merge pull request #1585 from Macr0Nerd/iss916
Browse files Browse the repository at this point in the history
Added to_string and added basic tests
  • Loading branch information
nlohmann committed May 24, 2019
2 parents 9f2179d + 2695250 commit 17c0849
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
15 changes: 15 additions & 0 deletions include/nlohmann/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7965,6 +7965,21 @@ class basic_json

/// @}
};

/*!
@brief user-defined to_string function for JSON values
This function implements a user-defined to_string for JSON objects.
@param[in] j a JSON object
@return a std::string object
*/

NLOHMANN_BASIC_JSON_TPL_DECLARATION
std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
{
return j.dump();
}
} // namespace nlohmann

///////////////////////
Expand Down
15 changes: 15 additions & 0 deletions single_include/nlohmann/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -20766,6 +20766,21 @@ class basic_json

/// @}
};

/*!
@brief user-defined to_string function for JSON values

This function implements a user-defined to_string for JSON objects.

@param[in] j a JSON object
@return a std::string object
*/

NLOHMANN_BASIC_JSON_TPL_DECLARATION
std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
{
return j.dump();
}
} // namespace nlohmann

///////////////////////
Expand Down
15 changes: 15 additions & 0 deletions test/src/unit-serialization.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -173,4 +173,19 @@ TEST_CASE("serialization")
test("\xE1\x80\xE2\xF0\x91\x92\xF1\xBF\x41", "\\ufffd" "\\ufffd" "\\ufffd" "\\ufffd" "\x41");
}
}

SECTION("to_string")
{
auto test = [&](std::string const & input, std::string const & expected)
{
using std::to_string;
json j = input;
CHECK(to_string(j) == "\"" + expected + "\"");
};

test("{\"x\":5,\"y\":6}", "{\\\"x\\\":5,\\\"y\\\":6}");
test("{\"x\":[10,null,null,null]}", "{\\\"x\\\":[10,null,null,null]}");
test("test", "test");
test("[3,\"false\",false]", "[3,\\\"false\\\",false]");
}
}

0 comments on commit 17c0849

Please sign in to comment.