| 1 | // |
| 2 | // Stringifier.cpp |
| 3 | // |
| 4 | // Library: JSON |
| 5 | // Package: JSON |
| 6 | // Module: Stringifier |
| 7 | // |
| 8 | // Copyright (c) 2012, Applied Informatics Software Engineering GmbH. |
| 9 | // and Contributors. |
| 10 | // |
| 11 | // SPDX-License-Identifier: BSL-1.0 |
| 12 | // |
| 13 | |
| 14 | |
| 15 | #include "Poco/JSON/Stringifier.h" |
| 16 | #include "Poco/JSON/Array.h" |
| 17 | #include "Poco/JSON/Object.h" |
| 18 | #include <iomanip> |
| 19 | |
| 20 | |
| 21 | using Poco::Dynamic::Var; |
| 22 | |
| 23 | |
| 24 | namespace Poco { |
| 25 | namespace JSON { |
| 26 | |
| 27 | |
| 28 | void Stringifier::stringify(const Var& any, std::ostream& out, unsigned int indent, int step, int options) |
| 29 | { |
| 30 | bool escapeUnicode = ((options & Poco::JSON_ESCAPE_UNICODE) != 0); |
| 31 | |
| 32 | if (step == -1) step = indent; |
| 33 | |
| 34 | if (any.type() == typeid(Object)) |
| 35 | { |
| 36 | Object& o = const_cast<Object&>(any.extract<Object>()); |
| 37 | o.setEscapeUnicode(escapeUnicode); |
| 38 | o.stringify(out, indent == 0 ? 0 : indent, step); |
| 39 | } |
| 40 | else if (any.type() == typeid(Array)) |
| 41 | { |
| 42 | Array& a = const_cast<Array&>(any.extract<Array>()); |
| 43 | a.setEscapeUnicode(escapeUnicode); |
| 44 | a.stringify(out, indent == 0 ? 0 : indent, step); |
| 45 | } |
| 46 | else if (any.type() == typeid(Object::Ptr)) |
| 47 | { |
| 48 | Object::Ptr& o = const_cast<Object::Ptr&>(any.extract<Object::Ptr>()); |
| 49 | o->setEscapeUnicode(escapeUnicode); |
| 50 | o->stringify(out, indent == 0 ? 0 : indent, step); |
| 51 | } |
| 52 | else if (any.type() == typeid(Array::Ptr)) |
| 53 | { |
| 54 | Array::Ptr& a = const_cast<Array::Ptr&>(any.extract<Array::Ptr>()); |
| 55 | a->setEscapeUnicode(escapeUnicode); |
| 56 | a->stringify(out, indent == 0 ? 0 : indent, step); |
| 57 | } |
| 58 | else if (any.isEmpty()) |
| 59 | { |
| 60 | out << "null" ; |
| 61 | } |
| 62 | else if (any.isNumeric() || any.isBoolean()) |
| 63 | { |
| 64 | std::string value = any.convert<std::string>(); |
| 65 | if (any.type() == typeid(char)) formatString(value, out, options); |
| 66 | else out << value; |
| 67 | } |
| 68 | else if (any.isString() || any.isDateTime() || any.isDate() || any.isTime()) |
| 69 | { |
| 70 | std::string value = any.convert<std::string>(); |
| 71 | formatString(value, out, options); |
| 72 | } |
| 73 | else |
| 74 | { |
| 75 | out << any.convert<std::string>(); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | |
| 80 | void Stringifier::formatString(const std::string& value, std::ostream& out, int options) |
| 81 | { |
| 82 | Poco::toJSON(value, out, options); |
| 83 | } |
| 84 | |
| 85 | |
| 86 | } } // namespace Poco::JSON |
| 87 | |