fork download
  1. class Json {
  2.  
  3. public static RootNode create() {
  4. return new RootNode();
  5. }
  6.  
  7. public interface Node<T extends Node<T>> {
  8. NotRootNode<T> object(String name);
  9.  
  10. T number(String name, int value);
  11. }
  12.  
  13. public static class RootNode extends AbstractNode<RootNode> implements Node<RootNode> {
  14.  
  15. public RootNode() {
  16. super(new StringBuilder());
  17. buf.append("{");
  18. }
  19.  
  20. public String build() {
  21. if (isNotEmpty)
  22. buf.setLength(buf.length() - 1);
  23. buf.append("}");
  24. return buf.toString();
  25. }
  26. }
  27.  
  28. public static class NotRootNode<P extends Node<P>> extends AbstractNode<NotRootNode<P>> implements Node<NotRootNode<P>> {
  29.  
  30. private final P parent;
  31.  
  32. public NotRootNode(StringBuilder buf, P parent) {
  33. super(buf);
  34. this.parent = parent;
  35. }
  36.  
  37. public P end() {
  38. if (isNotEmpty)
  39. buf.setLength(buf.length() - 1);
  40. buf.append("},");
  41. return parent;
  42. }
  43. }
  44.  
  45. private static class AbstractNode<T extends AbstractNode<T>> implements Node<T> {
  46.  
  47. protected final StringBuilder buf;
  48. protected boolean isNotEmpty;
  49.  
  50. public AbstractNode(StringBuilder buf) {
  51. this.buf = buf;
  52. this.isNotEmpty = false;
  53. }
  54.  
  55. @Override
  56. public T number(String name, int value) {
  57. isNotEmpty = true;
  58. buf.append('\"').append(name).append("\":").append(value).append(',');
  59. return self();
  60. }
  61.  
  62. @Override
  63. public NotRootNode<T> object(String name) {
  64. isNotEmpty = true;
  65. buf.append('\"').append(name).append("\":{");
  66. return new NotRootNode<>(buf, self());
  67. }
  68.  
  69. @SuppressWarnings("unchecked")
  70. protected T self() {
  71. return (T) this;
  72. }
  73. }
  74. }
  75.  
  76. class Scratch {
  77. public static void main(String[] args) {
  78. String str = Json.create()
  79. .number("a", 4)
  80. .object("b")
  81. .number("a", 4)
  82. .number("b", 5)
  83. .end()
  84. .number("c", 5)
  85. .build();
  86. System.out.println(str);
  87. }
  88. }
Success #stdin #stdout 0.04s 711168KB
stdin
Standard input is empty
stdout
{"a":4,"b":{"a":4,"b":5},"c":5}