programing

Java용 JSON 문자열 정리/포맷터

golfzon 2023. 3. 5. 10:52
반응형

Java용 JSON 문자열 정리/포맷터

각 속성/값 쌍이 고유한 줄에 있도록 정리/포맷하는 유효한 JSON 문자열이 있습니다(현재 공백/줄 바꿈 없이 한 줄에 있음).

Apache Sling을 사용하고 있습니다.JSONObjectJSON 오브젝트를 모델링하여 스트링으로 변환합니다.따라서 슬링이JSONObject깔끔한 스트링을 출력하도록 설정할 수 있습니다(그렇다고는 생각하지 않습니다).

서드파티 lib가 필요한 경우 가능한 한 의존관계가 적은 lib가 좋습니다(예를 들어 std JDK libs만 필요한 잭슨).

gson을 사용하여 다음 작업을 수행할 수 있습니다.

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

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

많은 JSON 라이브러리에는 특별한 기능이 있습니다..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));

외부 도서관은 필요 없습니다.

슬링의 JSONObject에 내장된 예쁜 프린터를 사용하세요.http://sling.apache.org/apidocs/sling5/org/apache/sling/commons/json/JSONObject.html#toString(int)

public java.displaces를 지정합니다.String toString(int ind Factor)이 JSONException을 슬로우합니다.

이 JSONObject의 JSON 텍스트를 예쁘게 인쇄합니다.경고:이 방법에서는 데이터 구조가 비클릭하다고 가정합니다.

파라미터:

indFactor - 각 들여쓰기 수준에 추가할 공간 수입니다.

반환: {(왼쪽 괄호)로 시작하여 }(오른쪽 괄호)로 끝나는 인쇄, 표시, 휴대, 전송 가능한 개체 표현입니다.

슬로우: JSONException: 객체에 비활성 번호가 포함되어 있는 경우.

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

+1은 JohnS의 gson 답변이지만, "표준" JSONObject 라이브러리를 사용하는 방법은 다음과 같습니다.

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

    }

}

사용방법:

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

출력:

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

잭슨 방식:

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

JSON 문자열에는 선행("")과 후행("])이 있습니다.이러한 항목을 제거한 후 String에서 분할 방식을 사용하여 항목을 배열로 구분합니다.그런 다음 어레이를 반복하여 데이터를 관련 영역에 배치할 수 있습니다.

CQ5 또는 JCR 기반의 CMS를 사용하는 경우:)

java json 파서를 사용하여 작업을 수행할 수 있습니다.JSONObject 클래스와 그것을 String으로 변환하기 위한 toString() 메서드가 있습니다.

더 참고하기 위해

http://json.org/java/

Underscore-java에는 statistic 메서드가 있습니다.U.formatJson(json)이치노

U.formatJson("{\"a\":{\"b\":\"data\"}}");

// {
//    "a": {
//      "b": "data"
//    }
// }

언급URL : https://stackoverflow.com/questions/8596161/json-string-tidy-formatter-for-java

반응형