简体   繁体   English

如何在 TextView 中设置格式化的 JSON 响应字符串?

[英]How to set formatted JSON response string in a TextView?

How to display JSON response string with formatting something similar to json.parser.online.fr ?如何显示格式类似于json.parser.online.fr JSON 响应字符串?

For example: How to display following code in textview ?例如:如何在 textview 中显示以下代码?

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

PS: Preferably color formatted. PS:最好是彩色格式。

In short ..简而言之 ..

1.How to format and display JSON string ? 1.如何格式化和显示JSON字符串?
2.How to format and display Java code ? 2.如何格式化和显示Java代码?

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();
}

Much simpler approch, there is a toString method with indent space param for JSONObject ,更简单的方法,有一个带有缩进空间参数的toString方法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同样适用于JSONArray

reference :参考 :

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

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

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. @suhas_sm 建议的方法很好,但如果键或值包含特殊字符之一,例如“{”,则无法正确缩进。

My solution (based on suhas_sm's method):我的解决方案(基于 suhas_sm 的方法):

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();
}

Do you want to parse it or simply show the raw JSON response?你想解析它还是简单地显示原始 JSON 响应? If the former:如果前者:

How to parse JSON in Android 如何在 Android 中解析 JSON

If you want it to be formatted, you can do it manually:如果您希望对其进行格式化,您可以手动进行:

example:例子:

{"J":5,"0":"N"} {"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.首先删除“{,}”,将这个数组 '"J":5,"0":"N"' 拆分为 ',' 然后进行着色只需检查一个值是否有引号并相应地选择。 Just a simple string manipulation.只是一个简单的字符串操作。

Then output:然后输出:

  • { {
  • foreach loop of the array items with colouring带有着色的数组项的 foreach 循环
  • } }

You can use XStream which is a library to serialize objects to XML and back again.您可以使用XStream库,它是一个将对象序列化为 XML 并再次返回的库。
But it can be used for JSON as well, look here XStream JSON Tutorial但它也可以用于 JSON,看这里XStream JSON 教程
More libraries can be found here http://www.json.org/更多的库可以在这里找到http://www.json.org/

EDIT编辑
For displaying in HTML you can use Javascript: JSON.stringify Function (JavaScript)要在 HTML 中显示,您可以使用 Javascript: JSON.stringify Function (JavaScript)

var jsonText = JSON.stringify(myJson, null, '\t'); \\ uses tab indent
document.write(jsonText);

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.这将帮助您格式化已经部分格式化的 JSON 字符串。 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.我在这里发布这个的原因是因为当我有一个部分格式化的输入 JSON 时,上述解决方案不起作用。

Here you go.干得好。 https://gist.github.com/rahulrvp/d10d6bea0e0b87883da5b8ce21f96c81 https://gist.github.com/rahulrvp/d10d6bea0e0b87883da5b8ce21f96c81

You can use ObjectMapper.您可以使用 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"]
}

You can use this method to prettify the JSON.您可以使用此方法来美化 JSON。 (Just an addition to @Rahul Tiwari 's answer) (只是对@Rahul Tiwari 的回答的补充)

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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM