11

How to display JSON response string with formatting something similar to https://jsonformatter.org/json-parser ?

For example: How to display following code in textview ?

{
    "age":100,
    "name":"mkyong.com",
    "messages":["msg 1","msg 2","msg 3"]
}

P.S: Preferably color formatted.

In short ..

1.How to format and display JSON string ?
2.How to format and display Java code ?

suhas_sm
  • 2,064
  • 1
  • 18
  • 23
  • JSON is a string essentially so since `TextViews` display strings I don't see your problem.What is the output you actually want. Could you add it to the question. Color Formatted? – cjds Jan 09 '13 at 10:07
  • The response I get is a single line string (no new lines, no indentation) - very lengthy. If I display it directly without formatting, it is unreadable. – suhas_sm Jan 09 '13 at 12:12

8 Answers8

28

I wrote the following utility method to format and indent (no colors yet):

public static String formatString(String text){

    StringBuilder json = new StringBuilder();
    String indentString = "";

    for (int i = 0; i < text.length(); i++) {
        char letter = text.charAt(i);
        switch (letter) {
            case '{':
            case '[':
                json.append("\n" + indentString + letter + "\n");
                indentString = indentString + "\t";
                json.append(indentString);
                break;
            case '}':
            case ']':
                indentString = indentString.replaceFirst("\t", "");
                json.append("\n" + indentString + letter);
                break;
            case ',':
                json.append(letter + "\n" + indentString);
                break;

            default:
                json.append(letter);
                break;
        }
    }

    return json.toString();
}
rahulrvp
  • 2,006
  • 1
  • 19
  • 26
suhas_sm
  • 2,064
  • 1
  • 18
  • 23
15

Much simpler approch, there is a toString method with indent space param for JSONObject,

can be used like this :

JSONObject jsonObject = new JSONObject(jsonString);
textView.setText(jsonObject.toString(4));// 4 is number of spaces for indent

same is applicable for JSONArray

reference :

https://developer.android.com/reference/org/json/JSONObject#toString(int)

https://alvinalexander.com/android/android-json-print-json-string-human-readable-format-debugging

Rahul Tiwari
  • 6,851
  • 3
  • 49
  • 78
3

The method @suhas_sm suggested is great, but fails to indent correctly if there's a key or a value that contains one of the special characters, "{" for example.

My solution (based on suhas_sm's method):

public static String formatString(String text){

    StringBuilder json = new StringBuilder();
    String indentString = "";

    boolean inQuotes = false;
    boolean isEscaped = false;

    for (int i = 0; i < text.length(); i++) {
        char letter = text.charAt(i);

        switch (letter) {
            case '\\':
                isEscaped = !isEscaped;
                break;
            case '"':
                if (!isEscaped) {
                    inQuotes = !inQuotes;
                }
                break;
            default:
                isEscaped = false;
                break;
        }

        if (!inQuotes && !isEscaped) {
            switch (letter) {
                case '{':
                case '[':
                    json.append("\n" + indentString + letter + "\n");
                    indentString = indentString + "\t";
                    json.append(indentString);
                    break;
                case '}':
                case ']':
                    indentString = indentString.replaceFirst("\t", "");
                    json.append("\n" + indentString + letter);
                    break;
                case ',':
                    json.append(letter + "\n" + indentString);
                    break;
                default:
                    json.append(letter);
                    break;
            }
        } else {
            json.append(letter);
        }
    }

    return json.toString();
}
Ron Tesler
  • 1,146
  • 1
  • 11
  • 24
2

Do you want to parse it or simply show the raw JSON response? If the former:

How to parse JSON in Android

If you want it to be formatted, you can do it manually:

example:

{"J":5,"0":"N"}


first remove "{,}", split this array '"J":5,"0":"N"' by ',' and then for the colouring just check if a value has quotations marks or not and choose accordingly. Just a simple string manipulation.

Then output:

  • {
  • foreach loop of the array items with colouring
  • }
Community
  • 1
  • 1
N3sh
  • 881
  • 8
  • 37
  • I don't want to parse it. I want to simply display the raw JSON response after formatting it -- like it is formatted in json.online.parse.fr – suhas_sm Jan 09 '13 at 10:05
  • So the only solution is use regex and do it manually ? Some JSON responses are lengthy enough to accommodate all JSON types. – suhas_sm Jan 09 '13 at 10:13
  • In programming there is never only 1 solution. But I would say that is the easiest way that crossed my mind. It shouldn't need more than 20 lines of code (not including the JSON request); and if you are not sure about ALL the JSON types, just add a 'default' case which handles all the other exceptions. Handle only, for example, strings, arrays and numbers for the colouring, that should be enough. – N3sh Jan 09 '13 at 10:16
  • Mmmh, '/t' ? :P More info? – N3sh Jan 09 '13 at 10:28
0

You can use XStream which is a library to serialize objects to XML and back again.
But it can be used for JSON as well, look here XStream JSON Tutorial
More libraries can be found here http://www.json.org/

EDIT
For displaying in HTML you can use Javascript: JSON.stringify Function (JavaScript)

var jsonText = JSON.stringify(myJson, null, '\t'); \\ uses tab indent
document.write(jsonText);
Haim Sulam
  • 316
  • 1
  • 5
0

I know this is too late but here is a solution I recently wrote. This will help you format the JSON strings which are already partially formatted. The reason why I'm posting this here is because the above solutions did not work when I had an input JSON which was partially formatted.

Here you go. https://gist.github.com/rahulrvp/d10d6bea0e0b87883da5b8ce21f96c81

rahulrvp
  • 2,006
  • 1
  • 19
  • 26
0

You can use ObjectMapper.

First thing is you convert your string to an Object and then do something like this.

String prettyJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);

Result.

{
    "age":100,
    "name":"mkyong.com",
    "messages":["msg 1","msg 2","msg 3"]
}
Aaron
  • 2,591
  • 4
  • 27
  • 45
0

You can use this method to prettify the JSON. (Just an addition to @Rahul Tiwari 's answer)

private String prettifyJson(String jsonString) {
    JSONObject jsonObject = null;

    try {
        jsonObject = new JSONObject(jsonString);
    } catch (JSONException ignored) {
    }

    try {
        if (jsonObject != null) {
            return jsonObject.toString(4);
        }
    } catch (JSONException ignored) {
    }

    return "empty";
}
Josef
  • 2,869
  • 2
  • 22
  • 23
Noah
  • 567
  • 5
  • 21