When can we use a JSONStringer in Java?


A JSONStringer provides a convenient way of producing JSON text and it can strictly follow to JSON syntax rules. Each instance of JSONStringer can produce one JSON text. A JSONStringer instance provides a value-method for appending values to the text and a key-method for adding keys before values in objects. There is an array () and endArray() methods that make and bound array values and object() and end object() methods that make and bound object values.

Example 1

import org.json.*;
public class JSONStringerTest1 {
   public static void main(String[] args) throws JSONException {
      JSONStringer stringer = new JSONStringer();
      String jsonStr = stringer
         .object() // Start JSON Object
            .key("Name")
            .value("Raja")
            .key("Age") //Add key-value pairs
            .value("25")
            .key("City")
            .value("Hyderabad")
         .endObject() // End JSON Object
         .toString();
      System.out.println(jsonStr);
   }
}

Output

{"Name":"Raja","Age":"25","City":"Hyderabad"}

Example 2

import org.json.*;
public class JSONStringerTest2 {
   public static void main(String[] args) throws JSONException {
      JSONStringer stringer = new JSONStringer();
      String jsonStr = stringer
         .array() //Start JSON Array
            .object() //Start JSON Object
               .key("Name").value("Adithya")
               .key("Age").value("25") //Add key-value pairs
               .key("Mobile").value("9959984000")
            .endObject() //End JSON Object
            .object()
               .key("Address").value("Madhapur")
               .key("City").value("Hyderabad")
            .endObject()
         .endArray() //End JSON Array
         .toString();
      System.out.println(jsonStr);
   }
}

Output

[{"Name":"Adithya","Age":"25","Mobile":"9959984000"},{"Address":"Madhapur","City":"Hyderabad"}]

Updated on: 04-Jul-2020

360 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements