Recently I came across an ugly string concatenation in one of our legacy codebase or the one I did not came across for a long time.
The string concatenation was there to construct as JSON string. The JSON string was then parsed as a message template for MQTT topics.
At first sight, I knew it gotta go and something bit more cleaner piece of code should replace it. So I was looking for options to do a better job. Then I found something below:
org.json library
Maven
1 | <dependency> |
Gradle
1 | compile "org.json:json:20090211" |
Using the JSONObject of this library I was able to replace the ugly string concatenation with something like below:
JSONObject in action
1 | new JSONObject() |
The above beautiful piece of code gives us the below JSON string.
1 | { |
Tip: Yes, you can also construct by nesting arrays into objects and vice versa. \O/
The keys are sorted by default. In JSON format that does no harm.
I do not have to show you the ugly concatenation to sell the point here but this org.json lib itself does pretty good job and I am sure you would agree as well.