/*
 *                                  Apache License
 *                            Version 2.0, January 2004
 *                         http://www.apache.org/licenses/
 *
 *    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
 *
 *    1. Definitions.
 *
 *       "License" shall mean the terms and conditions for use, reproduction,
 *       and distribution as defined by Sections 1 through 9 of this document.
 *
 *       "Licensor" shall mean the copyright owner or entity authorized by
 *       the copyright owner that is granting the License.
 *
 *       "Legal Entity" shall mean the union of the acting entity and all
 *       other entities that control, are controlled by, or are under common
 *       control with that entity. For the purposes of this definition,
 *       "control" means (i) the power, direct or indirect, to cause the
 *       direction or management of such entity, whether by contract or
 *       otherwise, or (ii) ownership of fifty percent (50%) or more of the
 *       outstanding shares, or (iii) beneficial ownership of such entity.
 *
 *       "You" (or "Your") shall mean an individual or Legal Entity
 *       exercising permissions granted by this License.
 *
 *       "Source" form shall mean the preferred form for making modifications,
 *       including but not limited to software source code, documentation
 *       source, and configuration files.
 *
 *       "Object" form shall mean any form resulting from mechanical
 *       transformation or translation of a Source form, including but
 *       not limited to compiled object code, generated documentation,
 *       and conversions to other media types.
 *
 *       "Work" shall mean the work of authorship, whether in Source or
 *       Object form, made available under the License, as indicated by a
 *       copyright notice that is included in or attached to the work
 *       (an example is provided in the Appendix below).
 *
 *       "Derivative Works" shall mean any work, whether in Source or Object
 *       form, that is based on (or derived from) the Work and for which the
 *       editorial revisions, annotations, elaborations, or other modifications
 *       represent, as a whole, an original work of authorship. For the purposes
 *       of this License, Derivative Works shall not include works that remain
 *       separable from, or merely link (or bind by name) to the interfaces of,
 *       the Work and Derivative Works thereof.
 *
 *       "Contribution" shall mean any work of authorship, including
 *       the original version of the Work and any modifications or additions
 *       to that Work or Derivative Works thereof, that is intentionally
 *       submitted to Licensor for inclusion in the Work by the copyright owner
 *       or by an individual or Legal Entity authorized to submit on behalf of
 *       the copyright owner. For the purposes of this definition, "submitted"
 *       means any form of electronic, verbal, or written communication sent
 *       to the Licensor or its representatives, including but not limited to
 *       communication on electronic mailing lists, source code control systems,
 *       and issue tracking systems that are managed by, or on behalf of, the
 *       Licensor for the purpose of discussing and improving the Work, but
 *       excluding communication that is conspicuously marked or otherwise
 *       designated in writing by the copyright owner as "Not a Contribution."
 *
 *       "Contributor" shall mean Licensor and any individual or Legal Entity
 *       on behalf of whom a Contribution has been received by Licensor and
 *       subsequently incorporated within the Work.
 *
 *    2. Grant of Copyright License. Subject to the terms and conditions of
 *       this License, each Contributor hereby grants to You a perpetual,
 *       worldwide, non-exclusive, no-charge, royalty-free, irrevocable
 *       copyright license to reproduce, prepare Derivative Works of,
 *       publicly display, publicly perform, sublicense, and distribute the
 *       Work and such Derivative Works in Source or Object form.
 *
 *    3. Grant of Patent License. Subject to the terms and conditions of
 *       this License, each Contributor hereby grants to You a perpetual,
 *       worldwide, non-exclusive, no-charge, royalty-free, irrevocable
 *       (except as stated in this section) patent license to make, have made,
 *       use, offer to sell, sell, import, and otherwise transfer the Work,
 *       where such license applies only to those patent claims licensable
 *       by such Contributor that are necessarily infringed by their
 *       Contribution(s) alone or by combination of their Contribution(s)
 *       with the Work to which such Contribution(s) was submitted. If You
 *       institute patent litigation against any entity (including a
 *       cross-claim or counterclaim in a lawsuit) alleging that the Work
 *       or a Contribution incorporated within the Work constitutes direct
 *       or contributory patent infringement, then any patent licenses
 *       granted to You under this License for that Work shall terminate
 *       as of the date such litigation is filed.
 *
 *    4. Redistribution. You may reproduce and distribute copies of the
 *       Work or Derivative Works thereof in any medium, with or without
 *       modifications, and in Source or Object form, provided that You
 *       meet the following conditions:
 *
 *       (a) You must give any other recipients of the Work or
 *           Derivative Works a copy of this License; and
 *
 *       (b) You must cause any modified files to carry prominent notices
 *           stating that You changed the files; and
 *
 *       (c) You must retain, in the Source form of any Derivative Works
 *           that You distribute, all copyright, patent, trademark, and
 *           attribution notices from the Source form of the Work,
 *           excluding those notices that do not pertain to any part of
 *           the Derivative Works; and
 *
 *       (d) If the Work includes a "NOTICE" text file as part of its
 *           distribution, then any Derivative Works that You distribute must
 *           include a readable copy of the attribution notices contained
 *           within such NOTICE file, excluding those notices that do not
 *           pertain to any part of the Derivative Works, in at least one
 *           of the following places: within a NOTICE text file distributed
 *           as part of the Derivative Works; within the Source form or
 *           documentation, if provided along with the Derivative Works; or,
 *           within a display generated by the Derivative Works, if and
 *           wherever such third-party notices normally appear. The contents
 *           of the NOTICE file are for informational purposes only and
 *           do not modify the License. You may add Your own attribution
 *           notices within Derivative Works that You distribute, alongside
 *           or as an addendum to the NOTICE text from the Work, provided
 *           that such additional attribution notices cannot be construed
 *           as modifying the License.
 *
 *       You may add Your own copyright statement to Your modifications and
 *       may provide additional or different license terms and conditions
 *       for use, reproduction, or distribution of Your modifications, or
 *       for any such Derivative Works as a whole, provided Your use,
 *       reproduction, and distribution of the Work otherwise complies with
 *       the conditions stated in this License.
 *
 *    5. Submission of Contributions. Unless You explicitly state otherwise,
 *       any Contribution intentionally submitted for inclusion in the Work
 *       by You to the Licensor shall be under the terms and conditions of
 *       this License, without any additional terms or conditions.
 *       Notwithstanding the above, nothing herein shall supersede or modify
 *       the terms of any separate license agreement you may have executed
 *       with Licensor regarding such Contributions.
 *
 *    6. Trademarks. This License does not grant permission to use the trade
 *       names, trademarks, service marks, or product names of the Licensor,
 *       except as required for reasonable and customary use in describing the
 *       origin of the Work and reproducing the content of the NOTICE file.
 *
 *    7. Disclaimer of Warranty. Unless required by applicable law or
 *       agreed to in writing, Licensor provides the Work (and each
 *       Contributor provides its Contributions) on an "AS IS" BASIS,
 *       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 *       implied, including, without limitation, any warranties or conditions
 *       of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
 *       PARTICULAR PURPOSE. You are solely responsible for determining the
 *       appropriateness of using or redistributing the Work and assume any
 *       risks associated with Your exercise of permissions under this License.
 *
 *    8. Limitation of Liability. In no event and under no legal theory,
 *       whether in tort (including negligence), contract, or otherwise,
 *       unless required by applicable law (such as deliberate and grossly
 *       negligent acts) or agreed to in writing, shall any Contributor be
 *       liable to You for damages, including any direct, indirect, special,
 *       incidental, or consequential damages of any character arising as a
 *       result of this License or out of the use or inability to use the
 *       Work (including but not limited to damages for loss of goodwill,
 *       work stoppage, computer failure or malfunction, or any and all
 *       other commercial damages or losses), even if such Contributor
 *       has been advised of the possibility of such damages.
 *
 *    9. Accepting Warranty or Additional Liability. While redistributing
 *       the Work or Derivative Works thereof, You may choose to offer,
 *       and charge a fee for, acceptance of support, warranty, indemnity,
 *       or other liability obligations and/or rights consistent with this
 *       License. However, in accepting such obligations, You may act only
 *       on Your own behalf and on Your sole responsibility, not on behalf
 *       of any other Contributor, and only if You agree to indemnify,
 *       defend, and hold each Contributor harmless for any liability
 *       incurred by, or claims asserted against, such Contributor by reason
 *       of your accepting any such warranty or additional liability.
 *
 *    END OF TERMS AND CONDITIONS
 *
 *    APPENDIX: How to apply the Apache License to your work.
 *
 *       To apply the Apache License to your work, attach the following
 *       boilerplate notice, with the fields enclosed by brackets "{}"
 *       replaced with your own identifying information. (Don't include
 *       the brackets!)  The text should be enclosed in the appropriate
 *       comment syntax for the file format. We also recommend that a
 *       file or class name and description of purpose be included on the
 *       same "printed page" as the copyright notice for easier
 *       identification within third-party archives.
 *
 *    Copyright {yyyy} {name of copyright owner}
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mineacademy.fo.jsonsimple;

import java.io.IOException;
import java.io.Writer;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

/**
 * Contains a few static methods for JSON values.
 *
 * @author FangYidong(fangyidong @ yahoo.com.cn)
 * @author Ralph Niemitz/RalleYTN(ralph.niemitz@gmx.de)
 * @version 2.0.0
 * @since 1.0.0
 */
public final class JsonSimpleUtil {

	// ==== 11.03.2018 | Ralph Niemitz/RalleYTN(ralph.niemitz@gmx.de)
	// -	Removed the "toJSONString" method because it was dead code
	// -	Moved the method "escape(String)" to the class "JSONUtil"
	// -	Renamed all "writeJSONString" methods to simply "write"
	// ====

	private JsonSimpleUtil() {
	}

	/**
	 * Encode an array into JSON text and write it to a {@linkplain Writer}.
	 *
	 * @param array  the array which should be written on the {@linkplain Writer}
	 * @param writer the {@linkplain Writer} to write to
	 * @throws IOException if an I/O error occurs
	 * @see #write(Object, Writer)
	 * @since 1.0.0
	 */
	public static void write(byte[] array, Writer writer) throws IOException {

		if (array == null)
			writer.write("null");
		else if (array.length == 0)
			writer.write("[]");
		else {

			writer.write("[");
			writer.write("" + array[0]);

			for (int index = 1; index < array.length; index++) {

				writer.write(",");
				writer.write("" + array[index]);
			}

			writer.write("]");
		}
	}

	/**
	 * Encode an array into JSON text and write it to a {@linkplain Writer}.
	 *
	 * @param array  the array which should be written on the {@linkplain Writer}
	 * @param writer the {@linkplain Writer} to write to
	 * @throws IOException if an I/O error occurs
	 * @see #write(Object, Writer)
	 * @since 1.0.0
	 */
	public static void write(short[] array, Writer writer) throws IOException {

		if (array == null)
			writer.write("null");
		else if (array.length == 0)
			writer.write("[]");
		else {

			writer.write("[");
			writer.write("" + array[0]);

			for (int index = 1; index < array.length; index++) {

				writer.write(",");
				writer.write("" + array[index]);
			}

			writer.write("]");
		}
	}

	/**
	 * Encode an array into JSON text and write it to a {@linkplain Writer}.
	 *
	 * @param array  the array which should be written on the {@linkplain Writer}
	 * @param writer the {@linkplain Writer} to write to
	 * @throws IOException if an I/O error occurs
	 * @see #write(Object, Writer)
	 * @since 1.0.0
	 */
	public static void write(int[] array, Writer writer) throws IOException {

		if (array == null)
			writer.write("null");
		else if (array.length == 0)
			writer.write("[]");
		else {

			writer.write("[");
			writer.write("" + array[0]);

			for (int index = 1; index < array.length; index++) {

				writer.write(",");
				writer.write("" + array[index]);
			}

			writer.write("]");
		}
	}

	/**
	 * Encode an array into JSON text and write it to a {@linkplain Writer}.
	 *
	 * @param array  the array which should be written on the {@linkplain Writer}
	 * @param writer the {@linkplain Writer} to write to
	 * @throws IOException if an I/O error occurs
	 * @see #write(Object, Writer)
	 * @since 1.0.0
	 */
	public static void write(long[] array, Writer writer) throws IOException {

		if (array == null)
			writer.write("null");
		else if (array.length == 0)
			writer.write("[]");
		else {

			writer.write("[");
			writer.write("" + array[0]);

			for (int index = 1; index < array.length; index++) {

				writer.write(",");
				writer.write("" + array[index]);
			}

			writer.write("]");
		}
	}

	/**
	 * Encode an array into JSON text and write it to a {@linkplain Writer}.
	 *
	 * @param array  the array which should be written on the {@linkplain Writer}
	 * @param writer the {@linkplain Writer} to write to
	 * @throws IOException if an I/O error occurs
	 * @see #write(Object, Writer)
	 * @since 1.0.0
	 */
	public static void write(float[] array, Writer writer) throws IOException {

		if (array == null)
			writer.write("null");
		else if (array.length == 0)
			writer.write("[]");
		else {

			writer.write("[");
			writer.write("" + array[0]);

			for (int index = 1; index < array.length; index++) {

				writer.write(",");
				writer.write("" + array[index]);
			}

			writer.write("]");
		}
	}

	/**
	 * Encode an array into JSON text and write it to a {@linkplain Writer}.
	 *
	 * @param array  the array which should be written on the {@linkplain Writer}
	 * @param writer the {@linkplain Writer} to write to
	 * @throws IOException if an I/O error occurs
	 * @see #write(Object, Writer)
	 * @since 1.0.0
	 */
	public static void write(double[] array, Writer writer) throws IOException {

		if (array == null)
			writer.write("null");
		else if (array.length == 0)
			writer.write("[]");
		else {

			writer.write("[");
			writer.write("" + array[0]);

			for (int index = 1; index < array.length; index++) {

				writer.write(",");
				writer.write("" + array[index]);
			}

			writer.write("]");
		}
	}

	/**
	 * Encode an array into JSON text and write it to a {@linkplain Writer}.
	 *
	 * @param array  the array which should be written on the {@linkplain Writer}
	 * @param writer the {@linkplain Writer} to write to
	 * @throws IOException if an I/O error occurs
	 * @see #write(Object, Writer)
	 * @since 1.0.0
	 */
	public static void write(boolean[] array, Writer writer) throws IOException {

		if (array == null)
			writer.write("null");
		else if (array.length == 0)
			writer.write("[]");
		else {

			writer.write("[");
			writer.write("" + array[0]);

			for (int index = 1; index < array.length; index++) {

				writer.write(",");
				writer.write("" + array[index]);
			}

			writer.write("]");
		}
	}

	/**
	 * Encode an array into JSON text and write it to a {@linkplain Writer}.
	 *
	 * @param array  the array which should be written on the {@linkplain Writer}
	 * @param writer the {@linkplain Writer} to write to
	 * @throws IOException if an I/O error occurs
	 * @see #write(Object, Writer)
	 * @since 1.0.0
	 */
	public static void write(char[] array, Writer writer) throws IOException {

		if (array == null)
			writer.write("null");
		else if (array.length == 0)
			writer.write("[]");
		else {

			writer.write("[");
			writer.write("" + array[0]);

			for (int index = 1; index < array.length; index++) {

				writer.write(",");
				writer.write("" + array[index]);
			}

			writer.write("]");
		}
	}

	/**
	 * Encode an array into JSON text and write it to a {@linkplain Writer}.
	 *
	 * @param array  the array which should be written on the {@linkplain Writer}
	 * @param writer the {@linkplain Writer} to write to
	 * @param <T>    type of the array
	 * @throws IOException if an I/O error occurs
	 * @see #write(Object, Writer)
	 * @since 1.0.0
	 */
	public static <T> void write(T[] array, Writer writer) throws IOException {

		if (array == null)
			writer.write("null");
		else if (array.length == 0)
			writer.write("[]");
		else {

			writer.write("[");
			JsonSimpleUtil.write(array[0], writer);

			for (int i = 1; i < array.length; i++) {

				writer.write(",");
				JsonSimpleUtil.write(array[i], writer);
			}

			writer.write("]");
		}
	}

	/**
	 * Encode a {@linkplain Collection} into JSON text and write it to a {@linkplain Writer}.
	 *
	 * @param collection the {@linkplain Collection} which should be written on the {@linkplain Writer}
	 * @param writer     the {@linkplain Writer} to write to
	 * @throws IOException if an I/O error occurs
	 * @since 1.0.0
	 */
	public static void write(Collection<?> collection, Writer writer) throws IOException {

		if (collection != null) {

			boolean first = true;
			final Iterator<?> iterator = collection.iterator();
			writer.write('[');

			while (iterator.hasNext()) {

				if (first)
					first = false;
				else
					writer.write(',');

				final Object value = iterator.next();

				if (value == null)
					writer.write("null");
				else
					JsonSimpleUtil.write(value, writer);
			}

			writer.write(']');

		} else
			writer.write("null");
	}

	/**
	 * Convert a {@linkplain Map} to a JSON string and write it on a {@linkplain Writer}. This method will not close or flush the given {@linkplain Writer}!
	 *
	 * @param map    the {@linkplain Map} to write
	 * @param writer the {@linkplain Writer} to which the {@linkplain Map} should be written to
	 * @throws IOException if an I/O error occurs
	 * @since 1.0.0
	 */
	public static void write(Map<?, ?> map, Writer writer) throws IOException {

		if (map != null) {

			boolean first = true;
			writer.write('{');

			for (final Map.Entry<?, ?> entry : map.entrySet()) {

				if (first)
					first = false;
				else
					writer.write(',');

				writer.write('\"');
				writer.write(JSONUtil.escape(String.valueOf(entry.getKey())));
				writer.write('\"');
				writer.write(':');

				JsonSimpleUtil.write(entry.getValue(), writer);
			}

			writer.write('}');

		} else
			writer.write("null");
	}

	/**
	 * Encode an {@linkplain Object} into JSON text and write it to a {@linkplain Writer}.
	 *
	 * @param value  the {@linkplain Object} to write on the {@linkplain Writer}
	 * @param writer the {@linkplain Writer} to write on.
	 * @throws IOException if an I/O error occurs
	 * @since 1.0.0
	 */
	public static void write(Object value, Writer writer) throws IOException {

		// ==== 11.03.2018 | Ralph Niemitz/RalleYTN(ralph.niemitz@gmx.de)
		// -	Made this method final
		// ====

		if (value == null)
			writer.write("null");
		else if (value instanceof String) {

			writer.write('\"');
			writer.write(JSONUtil.escape((String) value));
			writer.write('\"');

		} else if (value instanceof Double)
			writer.write(((Double) value).isInfinite() || ((Double) value).isNaN() ? "null" : value.toString());
		else if (value instanceof Float)
			writer.write(((Float) value).isInfinite() || ((Float) value).isNaN() ? "null" : value.toString());
		else if (value instanceof Number)
			writer.write(value.toString());
		else if (value instanceof Boolean)
			writer.write(value.toString());
		else if (value instanceof JSONObject)
			((JSONObject) value).write(writer);
		else if (value instanceof JSONArray)
			((JSONArray) value).write(writer);
		else if (value instanceof Map)
			JsonSimpleUtil.write((Map<Object, Object>) value, writer);
		else if (value instanceof Collection)
			JsonSimpleUtil.write((Collection<Object>) value, writer);
		else if (value instanceof byte[])
			JsonSimpleUtil.write((byte[]) value, writer);
		else if (value instanceof short[])
			JsonSimpleUtil.write((short[]) value, writer);
		else if (value instanceof int[])
			JsonSimpleUtil.write((int[]) value, writer);
		else if (value instanceof long[])
			JsonSimpleUtil.write((long[]) value, writer);
		else if (value instanceof float[])
			JsonSimpleUtil.write((float[]) value, writer);
		else if (value instanceof double[])
			JsonSimpleUtil.write((double[]) value, writer);
		else if (value instanceof boolean[])
			JsonSimpleUtil.write((boolean[]) value, writer);
		else if (value instanceof char[])
			JsonSimpleUtil.write((char[]) value, writer);
		else if (value.getClass().isArray())
			JsonSimpleUtil.write((Object[]) value, writer);
		else {

			writer.write('"');
			writer.write(JSONUtil.escape(value.toString()));
			writer.write('"');
		}
	}

	/**
	 * Tries to parse a value to an instance of {@linkplain JSONObject}.
	 *
	 * @param value the value that should be parsed
	 * @return the parsed value, or {@code null} if it could not be parsed
	 * @since 1.0.0
	 */
	public static JSONObject getObject(Object value) {

		if (value != null)
			if (value instanceof JSONObject)
				return (JSONObject) value;
			else if (value instanceof Map)
				return new JSONObject((Map<?, ?>) value);

		return null;
	}

	/**
	 * Tries to parse a value to an instance of {@linkplain JSONArray}.
	 *
	 * @param value the value that should be parsed
	 * @return the parsed value, or {@code null} if it could not be parsed
	 * @since 1.0.0
	 */
	public static JSONArray getArray(Object value) {

		if (value != null)
			if (value instanceof JSONArray)
				return (JSONArray) value;
			else if (value instanceof boolean[])
				return new JSONArray((boolean[]) value);
			else if (value instanceof byte[])
				return new JSONArray((byte[]) value);
			else if (value instanceof char[])
				return new JSONArray((char[]) value);
			else if (value instanceof short[])
				return new JSONArray((short[]) value);
			else if (value instanceof int[])
				return new JSONArray((int[]) value);
			else if (value instanceof long[])
				return new JSONArray((long[]) value);
			else if (value instanceof float[])
				return new JSONArray((float[]) value);
			else if (value instanceof double[])
				return new JSONArray((double[]) value);
			else if (value instanceof Collection)
				return new JSONArray((Collection<?>) value);
			else if (value.getClass().isArray())
				return new JSONArray(value);

		return null;
	}

	/**
	 * Tries to parse a value to an instance of {@linkplain Boolean}.
	 *
	 * @param value the value that should be parsed
	 * @return the parsed value, or {@code null} if it could not be parsed
	 * @since 1.0.0
	 */
	public static Boolean getBoolean(Object value) {

		if (value != null)
			if (value instanceof Boolean)
				return (boolean) value;
			else if (value instanceof String)
				return Boolean.parseBoolean((String) value);
			else if (value instanceof Number)
				return ((Number) value).longValue() == 1L;

		return null;
	}

	/**
	 * Tries to parse a value to an instance of {@linkplain Byte}.
	 *
	 * @param value the value that should be parsed
	 * @return the parsed value, or {@code null} if it could not be parsed
	 * @since 1.0.0
	 */
	public static Byte getByte(Object value) {

		if (value != null)
			if (value instanceof Number)
				return ((Number) value).byteValue();
			else if (value instanceof String)
				return Byte.parseByte((String) value);
			else if (value instanceof Boolean)
				return (boolean) value ? (byte) 1 : (byte) 0;

		return null;
	}

	/**
	 * Tries to parse a value to an instance of {@linkplain Short}.
	 *
	 * @param value the value that should be parsed
	 * @return the parsed value, or {@code null} if it could not be parsed
	 * @since 1.0.0
	 */
	public static Short getShort(Object value) {

		if (value != null)
			if (value instanceof Number)
				return ((Number) value).shortValue();
			else if (value instanceof String)
				return Short.parseShort((String) value);
			else if (value instanceof Boolean)
				return (boolean) value ? (short) 1 : (short) 0;

		return null;
	}

	/**
	 * Tries to parse a value to an instance of {@linkplain Integer}.
	 *
	 * @param value the value that should be parsed
	 * @return the parsed value, or {@code null} if it could not be parsed
	 * @since 1.0.0
	 */
	public static Integer getInteger(Object value) {

		if (value != null)
			if (value instanceof Number)
				return ((Number) value).intValue();
			else if (value instanceof String)
				return Integer.parseInt((String) value);
			else if (value instanceof Boolean)
				return (boolean) value ? 1 : 0;

		return null;
	}

	/**
	 * Tries to parse a value to an instance of {@linkplain Long}.
	 *
	 * @param value the value that should be parsed
	 * @return the parsed value, or {@code null} if it could not be parsed
	 * @since 1.0.0
	 */
	public static Long getLong(Object value) {

		if (value != null)
			if (value instanceof Number)
				return ((Number) value).longValue();
			else if (value instanceof String)
				return Long.parseLong((String) value);
			else if (value instanceof Boolean)
				return (boolean) value ? 1L : 0L;

		return null;
	}

	/**
	 * Tries to parse a value to an instance of {@linkplain Float}.
	 *
	 * @param value the value that should be parsed
	 * @return the parsed value, or {@code null} if it could not be parsed
	 * @since 1.0.0
	 */
	public static Float getFloat(Object value) {

		if (value != null)
			if (value instanceof Number)
				return ((Number) value).floatValue();
			else if (value instanceof String)
				return Float.parseFloat((String) value);
			else if (value instanceof Boolean)
				return (boolean) value ? 1F : 0F;

		return null;
	}

	/**
	 * Tries to parse a value to an instance of {@linkplain Double}.
	 *
	 * @param value the value that should be parsed
	 * @return the parsed value, or {@code null} if it could not be parsed
	 * @since 1.0.0
	 */
	public static Double getDouble(Object value) {

		if (value != null)
			if (value instanceof Number)
				return ((Number) value).doubleValue();
			else if (value instanceof String)
				return Double.parseDouble((String) value);
			else if (value instanceof Boolean)
				return (boolean) value ? 1D : 0D;

		return null;
	}

	/**
	 * Tries to parse a value to an instance of {@linkplain String}.
	 *
	 * @param value the value that should be parsed
	 * @return the parsed value, or {@code null} if it could not be parsed
	 * @since 1.0.0
	 */
	public static String getString(Object value) {

		if (value != null)
			return value.toString();

		return null;
	}

	/**
	 * Tries to parse a value to an instance of {@linkplain Date}.
	 *
	 * @param value  the value that should be parsed
	 * @param format the {@linkplain DateFormat} that should be used to parse the value
	 * @return an instance of {@linkplain Date} or {@code null} if the input value was already {@code null}
	 * @throws ParseException if the value could not be parsed to an instance of {@linkplain Date}
	 * @since 1.0.0
	 */
	public static Date getDate(Object value, DateFormat format) throws ParseException {

		if (value != null)
			return value instanceof Date ? (Date) value : format.parse(value.toString());

		return null;
	}

	/**
	 * Tries to parse a value to an enum.
	 *
	 * @param value the value that should be parsed
	 * @param type  the enum class
	 * @param <T>   the enum type
	 * @return the enum or {@code null} if the value could not be parsed
	 * @since 1.0.0
	 */
	public static <T extends Enum<T>> T getEnum(Object value, Class<T> type) {

		if (value != null)
			for (final Object enumConstant : type.getEnumConstants())
				if (((T) enumConstant).name().equals(value.toString()))
					return (T) enumConstant;

		return null;
	}

	/**
	 * Escapes a string according to the <a href="https://tools.ietf.org/html/rfc7159#section-8.1">JSON specification</a>.
	 *
	 * @param string  the string which should be escaped
	 * @param builder the {@linkplain StringBuilder} on which the result will be written
	 * @since 1.0.0
	 */
	public static void escape(String string, StringBuilder builder) {

		for (int index = 0; index < string.length(); index++) {

			final char character = string.charAt(index);

			// If is faster than Switch
			if (character == '"')
				builder.append("\\\"");
			else if (character == '\\')
				builder.append("\\\\");
			else if (character == '\b')
				builder.append("\\b");
			else if (character == '\f')
				builder.append("\\f");
			else if (character == '\n')
				builder.append("\\n");
			else if (character == '\r')
				builder.append("\\r");
			else if (character == '\t')
				builder.append("\\t");
			else if (character == '/')
				builder.append("\\/");
			else if (character >= '\u0000' && character <= '\u001F' ||
					character >= '\u007F' && character <= '\u009F' ||
					character >= '\u2000' && character <= '\u20FF') {

				final String hex = Integer.toHexString(character);
				builder.append("\\u");

				for (int k = 0; k < 4 - hex.length(); k++)
					builder.append('0');

				builder.append(hex.toUpperCase());

			} else
				builder.append(character);
		}
	}
}
