Home >Java >javaTutorial >When can we use JSONStringer in Java?
JSONStringer provides a convenient way to generate JSON text and can strictly follow JSON syntax rules. Each instance of JSONStringer can generate a JSON text. JSONStringer instances provide value methods for appending values to text and key methods for adding keys before values in an object. There is an array () and endArray() method to create and bind array values and object() and ultimately Object() Method to create and bind object values.
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); } }
{"Name":"Raja","Age":"25","City":"Hyderabad"}<strong> </strong>
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); } }
[{"Name":"Adithya","Age":"25","Mobile":"9959984000"},{"Address":"Madhapur","City":"Hyderabad"}]
The above is the detailed content of When can we use JSONStringer in Java?. For more information, please follow other related articles on the PHP Chinese website!