Simplify Complex JSON Creation in Java with Double‑Brace Initialization

When integrating a third‑party API, building deeply nested JSON structures can become cumbersome, but using Java's double‑brace initialization for maps and JSONObjects dramatically reduces boilerplate code while keeping the payload readable and maintainable.

FunTester
FunTester
FunTester
Simplify Complex JSON Creation in Java with Double‑Brace Initialization

Double‑brace initialization for collections

When constructing request payloads for a third‑party API, creating many JSONObject and JSONArray instances can make the code verbose. Java allows a technique called double‑brace initialization, which creates an anonymous subclass and runs an instance‑initializer block, enabling inline population of collections.

HashMap<String, Integer> map = new HashMap<String, Integer>() {{
    put("322", 1322);
    put("3242", 1232);
    put("32422", 1264);
}};

This reduces the number of temporary variable declarations and improves indentation, though the readability impact is subjective.

Compact construction of nested JSON objects

A conventional way to build a complex JSON structure involves multiple statements:

JSONObject funtester = new JSONObject();
 funtester.put("class", 23);
 ArrayList<Integer> teacher = new ArrayList<>();
 teacher.add(32312);
 teacher.add(12312);
 funtester.put("teacher", teacher);
 // ... similar code for students and data ...

Using double‑brace initialization the same structure can be expressed in a single expression:

JSONObject funtester = new JSONObject() {{
    put("class", 23);
    put("teacher", new ArrayList<Integer>() {{
        add(32312);
        add(12312);
    }});
    put("students", new ArrayList<Integer>() {{
        add(123);
        add(125);
    }});
    put("data", new JSONObject() {{
        put("max", 123);
        put("avg", 100);
        put("scores", new ArrayList<Integer>() {{
            add(123);
            add(77);
        }});
    }});
}};

Encapsulating the payload in a helper method

The author wraps the whole request payload in a method sendRtf. The method builds a nested JSON object that represents a “post” message. Optional hyperlink and @‑mention elements are added only when the corresponding parameters are non‑blank.

public void sendRtf(String title, String content, String url, String uid) {
    send(new JSONObject() {{
        put("msg_type", "post");
        put("content", new JSONObject() {{
            put("post", new JSONObject() {{
                put("zh_cn", new JSONObject() {{
                    put("title", title);
                    put("content", new JSONArray() {{
                        add(new JSONArray() {{
                            add(new JSONObject() {{
                                put("tag", "text");
                                put("text", content);
                            }});
                            if (StringUtils.isNotBlank(url)) {
                                add(new JSONObject() {{
                                    put("tag", "a");
                                    put("text", "点击查看详情");
                                    put("href", url);
                                }});
                            }
                            if (StringUtils.isNotBlank(uid)) {
                                add(new JSONObject() {{
                                    put("tag", "at");
                                    put("user_id", uid);
                                }});
                            }
                        }});
                    }});
                }});
            }});
        }});
    }});
}

Considerations

Double‑brace initialization creates an anonymous inner class, which may increase the size of the generated bytecode and retain a reference to the enclosing instance.

It is not suitable for performance‑critical code or for classes that must be serializable.

Readability varies among developers; some prefer explicit step‑by‑step construction.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaJSONCode OptimizationMAPdouble-brace-initializationjsonobject
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.