Java Json to Object stringForJSON(String input)

Here you can find the source of stringForJSON(String input)

Description

Format String for JSON Serialization

License

LGPL

Parameter

Parameter Description
input - string to format

Return

result String

Declaration

private static String stringForJSON(String input) 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import java.text.CharacterIterator;

import java.text.StringCharacterIterator;

public class Main {
    /**/*w  ww.j a  va 2  s. c om*/
     * Format String for JSON Serialization
     * @param input - string to format
     * @return result String
     */
    private static String stringForJSON(String input) {
        if (input == null || input.isEmpty())
            return "";

        final int len = input.length();
        final StringBuilder result = new StringBuilder(len + len / 4);
        final StringCharacterIterator iterator = new StringCharacterIterator(input);
        char ch = iterator.current();
        while (ch != CharacterIterator.DONE) {
            if (ch == '\n') {
                result.append("\\n");
            } else if (ch == '\r') {
                result.append("\\r");
            } else if (ch == '\'') {
                result.append("\\\'");
            } else if (ch == '"') {
                result.append("\\\"");
            } else {
                result.append(ch);
            }
            ch = iterator.next();
        }
        return result.toString();
    }
}

Related

  1. jsonToObject(String json, Class toValueType)
  2. jsonToObject(String jsonString, Class classOfT)
  3. jsonToPojo(String jsonData, Class beanType)
  4. parse(String jsonLine)
  5. readValue(String jsonStr, Class valueType)