Java String Quote quoteIfNeeded(String source)

Here you can find the source of quoteIfNeeded(String source)

Description

Add quotes around the object iff it's not a JSON object.

License

Apache License

Parameter

Parameter Description
source a parameter

Declaration

static String quoteIfNeeded(String source) 

Method Source Code

//package com.java2s;
/**/*  ww w  . j av  a  2 s. c om*/
 * Copyright 2009-2012 the original author or authors.
 *
 * 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.
 */

public class Main {
    /**
     * Add quotes around the object iff it's not a JSON object.
     *
     * @param source
     * @return
     */
    static String quoteIfNeeded(String source) {
        String trimmed = source.trim();

        if (isObject(trimmed) || isArray(trimmed) || isString(trimmed) || isBoolean(trimmed) || isNull(trimmed)
                || isNumber(trimmed)) {
            return source;
        } else {
            return "\"" + source + "\"";
        }
    }

    /**
     * Add quotes around the object iff it's not a JSON object.
     *
     * @param source
     * @return
     */
    static Object quoteIfNeeded(Object source) {
        if (source instanceof String) {
            return quoteIfNeeded((String) source);
        } else {
            return source;
        }
    }

    private static boolean isObject(String trimmed) {
        return trimmed.startsWith("{");
    }

    private static boolean isArray(String trimmed) {
        return trimmed.startsWith("[");
    }

    private static boolean isString(String trimmed) {
        return trimmed.startsWith("\"");
    }

    private static boolean isBoolean(String trimmed) {
        return trimmed.equals("true") || trimmed.equals("false");
    }

    private static boolean isNull(String trimmed) {
        return trimmed.equals("null");
    }

    private static boolean isNumber(String source) {
        try {
            Double.parseDouble(source);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }
}

Related

  1. quoteIdentifier(String s)
  2. quoteIdentifier(String s)
  3. quoteIfCeylonKeyword(String name)
  4. quoteIfNeeded(String id)
  5. quoteIfNeeded(String input)
  6. quoteIfNeeded(String value)
  7. quoteIfNeeded(StringBuilder buf, String str, String delim)
  8. quoteIfNotNull(String str)
  9. quoteIfNotNull(String text)