Skip to content

Instantly share code, notes, and snippets.

@dkzwm
Last active September 14, 2021 01:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dkzwm/02cf2f8535e9e9f1b9d1e0915ab2c686 to your computer and use it in GitHub Desktop.
Save dkzwm/02cf2f8535e9e9f1b9d1e0915ab2c686 to your computer and use it in GitHub Desktop.
IntelliJ IDEA toString templates for JSON output
public java.lang.String toString() {
final java.lang.StringBuilder sb = new java.lang.StringBuilder("{");
#set ($i = 0)
#foreach ($member in $members)#if ($i == 0)
sb.append("#####
#else
sb.append(",####
#end#if ($member.stringArray)
\"$member.name\":");
#elseif ($member.string || $member.date)
\"$member.name\":\"")
#elseif($member.map||$member.collection)
\"$member.name\":");
#else
\"$member.name\":")
#end#if ($member.stringArray)
if (($member.accessor) != null && ($member.accessor).length > 0) {
sb.append("[");
final int stringArrayLength = ($member.accessor).length;
for (int i = 0; i < stringArrayLength; i++) {
sb.append("\"").append(($member.accessor)[i]).append("\"");
if (i < stringArrayLength - 1) {
sb.append(",");
} else {
sb.append("]");
}
}
} else {
sb.append("[]");
}
#elseif ($member.primitiveArray || $member.objectArray)
.append(java.util.Arrays.toString($member.accessor));
#elseif ($member.string || $member.date)
.append(java.util.Objects.toString($member.accessor,"")).append('\"');
#elseif($member.list)
if (($member.accessor) != null && !($member.accessor).isEmpty()) {
sb.append("[");
final int listSize = ($member.accessor).size();
for (int i = 0; i < listSize; i++) {
final Object listValue=($member.accessor).get(i);
if (listValue instanceof CharSequence) {
sb.append("\"").append(java.util.Objects.toString(listValue,"")).append("\"");
} else {
sb.append(java.util.Objects.toString(listValue,""));
}
if (i < listSize - 1) {
sb.append(",");
} else {
sb.append("]");
}
}
} else {
sb.append("[]");
}
#elseif($member.map)
if (($member.accessor) != null && !($member.accessor).isEmpty()) {
sb.append("{");
final Set<?> mapKeySet=($member.accessor).keySet();
for (java.lang.Object mapKey: mapKeySet) {
final Object mapValue=($member.accessor).get(mapKey);
sb.append("\"").append(mapKey).append("\":\"").append(java.util.Objects.toString(mapValue,"")).append("\",");
}
sb.replace(sb.length() - 1, sb.length(), "}");
} else {
sb.append("{}");
}
#elseif($member.collection)
if (($member.accessor) != null && !($member.accessor).isEmpty()) {
sb.append("[");
for (java.lang.Object collectionValue: $member.accessor) {
sb.append("\"").append(java.util.Objects.toString(collectionValue,"")).append("\",");
}
sb.replace(sb.length() - 1, sb.length(), "]");
} else {
sb.append("[]");
}
#else
.append($member.accessor);
#end#set ($i = $i + 1)
#end
sb.append('}');
return sb.toString();
}
@IAFahim
Copy link

IAFahim commented Sep 12, 2021

StringBuilder why why hummm...

class Residents implements Validate {
    private String name;
    private String nid;
    private double salary;
    private long[] array = new long[]{324, 423};
}

Yours is

public String toString() {
        final StringBuilder sb = new StringBuilder("{");
        sb.append("\"name\":\"")
                .append(Objects.toString(name, "")).append('\"');
        sb.append(",\"nid\":\"")
                .append(Objects.toString(nid, "")).append('\"');
        sb.append(",\"salary\":")
                .append(salary);
        sb.append(",\"array\":")
                .append(Arrays.toString(array));
        sb.append('}');
        return sb.toString();
    }

For this class it should be this, It's much better

return "{" + "\"name\":\"" +
                name + '\"' +
                ",\"nid\":\"" +
                nid + '\"' +
                ",\"salary\":" +
                salary +
                ",\"array\":" +
                Arrays.toString(array) +
                '}';

I can't even edit the template code BTW

@IAFahim
Copy link

IAFahim commented Sep 12, 2021

Doesn't work for array of string

@IAFahim
Copy link

IAFahim commented Sep 12, 2021

Hayyy I am just admiring your code you did great

@dkzwm
Copy link
Author

dkzwm commented Sep 13, 2021

Why I used StringBuilder, because on modern JVM, the + operation of String will be optimized to StringBuilder, and using StringBuilder is more beautiful and easy to understand. Now this template already supports array of String.

@IAFahim
Copy link

IAFahim commented Sep 13, 2021

But it isn't thread safe, naa.
Wait local StringBuilder are safe. I got warnings form intillj and got worried sorry

@dkzwm
Copy link
Author

dkzwm commented Sep 14, 2021

Thread safety should be guaranteed by the developer. JSON serialization operation feels that in most cases there will be no multi-threaded operation of the same serialized object. If you want to operate the same serialized object in different threads, then is necessary to lock the write and read operations, but this violates the original intention of fast serialization. This template is only used to generate the JSON string the fastest and does not rely on the serialization tool library. It cannot solve 100% of the problems, but it is suitable and convenient for most scenarios.

@IAFahim
Copy link

IAFahim commented Sep 14, 2021

Thank you. I was using it as toString 🤦🏻‍♂️
I finally understood the use case. It's quite elegant to use case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment