web-dev-qa-db-fra.com

JSON String tidy / formatter for Java

J'ai une chaîne JSON valide que je veux ranger/formater de telle sorte que chaque paire propriété/valeur soit sur sa propre ligne, etc. (elle est actuellement sur une ligne sans espaces/sauts de ligne).

J'utilise Apache Sling JSONObject pour modéliser mon objet JSON et le transformer en chaîne, donc si le Sling JSONObject peut être défini pour produire une chaîne bien rangée (ce que je ne pense pas ), cela fonctionnerait aussi.

Si j'ai besoin d'une bibliothèque tierce, je préférerais une avec aussi peu de dépendances que possible (comme Jackson qui ne nécessite que les bibliothèques JDK std).

19
empire29

Vous n'avez pas besoin d'une bibliothèque extérieure.

Utilisez la jolie imprimante intégrée dans JSONObject de Sling: http://sling.Apache.org/apidocs/sling5/org/Apache/sling/commons/json/JSONObject.html#toString (int )

public Java.lang.String toString (int indentFactor) lève JSONException

Créez un texte JSON assez imprimé de ce JSONObject. Avertissement: cette méthode suppose que la structure des données est acyclique.

Paramètres:

indentFactor - Le nombre d'espaces à ajouter à chaque niveau d'indentation.

Renvoie: une représentation imprimable, affichable, portable et transmissible de l'objet, commençant par {(accolade gauche) et se terminant par} (accolade droite).

Lance: JSONException - Si l'objet contient un numéro non valide.

23
Freiheit

Avec gson, vous pouvez faire:

JsonParser parser = new JsonParser();
Gson gson = new GsonBuilder().setPrettyPrinting().create();

JsonElement el = parser.parse(jsonString);
jsonString = gson.toJson(el); // done
38
Ali Shakiba

De nombreuses bibliothèques JSON ont une méthode spéciale .toString(int indentation)

// if it's not already, convert to a JSON object
JSONObject jsonObject = new JSONObject(jsonString);
// To string method prints it with specified indentation
System.out.println(jsonObject.toString(4));
20
Oded Breiner

+1 pour la réponse gson de JohnS, mais voici un moyen avec la bibliothèque JSONObject "standard":

public class JsonFormatter{

    public static String format(final JSONObject object) throws JSONException{
        final JsonVisitor visitor = new JsonVisitor(4, ' ');
        visitor.visit(object, 0);
        return visitor.toString();
    }

    private static class JsonVisitor{

        private final StringBuilder builder = new StringBuilder();
        private final int indentationSize;
        private final char indentationChar;

        public JsonVisitor(final int indentationSize, final char indentationChar){
            this.indentationSize = indentationSize;
            this.indentationChar = indentationChar;
        }

        private void visit(final JSONArray array, final int indent) throws JSONException{
            final int length = array.length();
            if(length == 0){
                write("[]", indent);
            } else{
                write("[", indent);
                for(int i = 0; i < length; i++){
                    visit(array.get(i), indent + 1);
                }
                write("]", indent);
            }

        }

        private void visit(final JSONObject obj, final int indent) throws JSONException{
            final int length = obj.length();
            if(length == 0){
                write("{}", indent);
            } else{
                write("{", indent);
                final Iterator<String> keys = obj.keys();
                while(keys.hasNext()){
                    final String key = keys.next();
                    write(key + " :", indent + 1);
                    visit(obj.get(key), indent + 1);
                    if(keys.hasNext()){
                        write(",", indent + 1);
                    }
                }
                write("}", indent);
            }

        }

        private void visit(final Object object, final int indent) throws JSONException{
            if(object instanceof JSONArray){
                visit((JSONArray) object, indent);
            } else if(object instanceof JSONObject){
                visit((JSONObject) object, indent);
            } else{
                if(object instanceof String){
                    write("\"" + (String) object + "\"", indent);
                } else{
                    write(String.valueOf(object), indent);
                }
            }

        }

        private void write(final String data, final int indent){
            for(int i = 0; i < (indent * indentationSize); i++){
                builder.append(indentationChar);
            }
            builder.append(data).append('\n');
        }

        @Override
        public String toString(){
            return builder.toString();
        }

    }

}

Usage:

public static void main(final String[] args) throws JSONException{
    final JSONObject obj =
            new JSONObject("{\"glossary\":{\"title\": \"example glossary\", \"GlossDiv\":{\"title\": \"S\", \"GlossList\":{\"GlossEntry\":{\"ID\": \"SGML\", \"SortAs\": \"SGML\", \"GlossTerm\": \"Standard Generalized Markup Language\", \"Acronym\": \"SGML\", \"Abbrev\": \"ISO 8879:1986\", \"GlossDef\":{\"para\": \"A meta-markup language, used to create markup languages such as DocBook.\", \"GlossSeeAlso\": [\"GML\", \"XML\"]}, \"GlossSee\": \"markup\"}}}}}");
    System.out.println(JsonFormatter.format(obj));
}

Production:

{
    glossary :
    {
        title :
        "example glossary"
        ,
        GlossDiv :
        {
            GlossList :
            {
                GlossEntry :
                {
                    SortAs :
                    "SGML"
                    ,
                    GlossDef :
                    {
                        GlossSeeAlso :
                        [
                            "GML"
                            "XML"
                        ]
                        ,
                        para :
                        "A meta-markup language, used to create markup languages such as DocBook."
                    }
                    ,
                    GlossSee :
                    "markup"
                    ,
                    GlossTerm :
                    "Standard Generalized Markup Language"
                    ,
                    ID :
                    "SGML"
                    ,
                    Acronym :
                    "SGML"
                    ,
                    Abbrev :
                    "ISO 8879:1986"
                }
            }
            ,
            title :
            "S"
        }
    }
}
7
Sean Patrick Floyd
    public static String formatJSONStr(final String json_str, final int indent_width) {
    final char[] chars = json_str.toCharArray();
    final String newline = System.lineSeparator();

    String ret = "";
    boolean begin_quotes = false;

    for (int i = 0, indent = 0; i < chars.length; i++) {
        char c = chars[i];

        if (c == '\"') {
            ret += c;
            begin_quotes = !begin_quotes;
            continue;
        }

        if (!begin_quotes) {
            switch (c) {
            case '{':
            case '[':
                ret += c + newline + String.format("%" + (indent += indent_width) + "s", "");
                continue;
            case '}':
            case ']':
                ret += newline + ((indent -= indent_width) > 0 ? String.format("%" + indent + "s", "") : "") + c;
                continue;
            case ':':
                ret += c + " ";
                continue;
            case ',':
                ret += c + newline + (indent > 0 ? String.format("%" + indent + "s", "") : "");
                continue;
            default:
                if (Character.isWhitespace(c)) continue;
            }
        }

        ret += c + (c == '\\' ? "" + chars[++i] : "");
    }

    return ret;
}
4
Janardhan

si vous utilisez CQ5 ou tout CMS basé sur JCR comme je suppose :)

vous pouvez utiliser Java analyseur json pour faire le travail. il a une classe JSONObject et une méthode toString () pour le convertir en String.

pour plus de référence, se référer

http://json.org/Java/

1
Rajesh Pantula

La voie jackson:

private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
...
OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(node);
1
Thorsten Hilker

La chaîne JSON aura un "[" et un "]" fin. Supprimez-les, puis utilisez la méthode de fractionnement de String pour séparer les éléments dans un tableau. Vous pouvez ensuite parcourir votre tableau et placer les données dans les zones pertinentes.

1
Travis J

Underscore-Java a la méthode statistique U.formatJson(json). Je suis le responsable de la bibliothèque.

0