We need to read JSON from STDIN. Input gives one line of ugliefied JSON. Output should be formatted JSON. Check the standard output link. Use 2 white spaces (not‘\t’) for one indentation.
SAMPLE INPUT:
{“group” : {list : [1,2,3]}, “list” : [“a”,”b”,”c”]}
SAMPLE OUTPUT:
{
“group” : {
List : [1,2,3]
},
“list” : [“a”,”b”,”c”]
}
Here is the code I am using:
public class JSONPetty {
public static void main(String[] args) {
String myJsObj = "{“group” : {list : [1,2,3]}, “list” : [“a”,”b”,”c”]}";
System.out.println(isMatched(myJsObj));
}
public static StringBuffer isMatched(String expression) {
final String opening = "{"; // opening delimiters
final String closing = "}"; // respective closing delimiters
StringBuffer temp = null;
Stack < Character > buffer = new Stack <Character > ();
for (char c: expression.toCharArray()) {
if (opening.indexOf(c)!= -1) // this is a left delimiter
{
try {
//Here temp is not appending its returning null value
temp.append("{" + "\n");
} catch (Exception e) {
System.out.println(e.toString());
}
}
if (closing.indexOf(c)!= -1) // this is a left delimiter
{
temp.append("}" + "\n");
}
}
return temp;
}
}
Also, need to know if anyone has any other better solutions.