Class JsonBuilder

java.lang.Object
com.aspectran.utils.json.JsonBuilder

public class JsonBuilder extends Object
A builder for creating JSON string.

ex)

     String json = new JsonBuilder();
         .object()
             .put("name", "value")
             .object("object")
                 .put("name", "value")
             .endObject()
             .array("array")
                 .put("value-1")
                 .put("value-2")
             .endArray()
         .endObject()
         .toString();
 

In the above example, the value of the json variable is:

    {"name": "value", "object": {"name": "value"}, "array": ["value-1", "value-2"]}

Note: object() & endObject() are a pair of methods, which means that they should show up at the same time. So does array() & endArray()

Created: 2024. 12. 14.

  • Constructor Details

    • JsonBuilder

      public JsonBuilder()
  • Method Details

    • setStringifyContext

      public void setStringifyContext(StringifyContext stringifyContext)
    • apply

      public JsonBuilder apply(StringifyContext stringifyContext)
    • prettyPrint

      public JsonBuilder prettyPrint(boolean prettyPrint)
    • indentString

      public JsonBuilder indentString(@Nullable String indentString)
    • nullWritable

      public JsonBuilder nullWritable(boolean nullWritable)
    • object

      public JsonBuilder object()
      Begins encoding a new object.
      Returns:
      this builder
    • object

      public JsonBuilder object(String name)
      Begins encoding a new object with the given name.
      Returns:
      this builder
    • endObject

      public JsonBuilder endObject()
      Ends encoding the current object.
      Returns:
      this builder
    • array

      public JsonBuilder array()
      Begins encoding a new array.
      Returns:
      this builder
    • array

      public JsonBuilder array(String name)
      Begins encoding a new array with the given name.
      Returns:
      this builder
    • endArray

      public JsonBuilder endArray()
      Ends encoding the current array.
      Returns:
      this builder
    • put

      public JsonBuilder put(Object value)
      Put a new value into an array. If it's not in an array, just put it as a single value.
      Parameters:
      value - the new value
      Returns:
      this builder
    • put

      public JsonBuilder put(String name, Object value)
      Put a new name-value pair in an object.
      Parameters:
      name - the name of the entry to put in the object
      value - the value of the entry to put in the object
      Returns:
      this builder
    • toString

      @Nullable public String toString()
      Overrides:
      toString in class Object
    • toJsonString

      public JsonString toJsonString()