Home > Java > javaTutorial > body text

When can we use JSONStringer in Java?

WBOY
Release: 2023-09-21 08:13:14
forward
1021 people have browsed it

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.

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);
   }
}
Copy after login

Output

{"Name":"Raja","Age":"25","City":"Hyderabad"}<strong>
</strong>
Copy after login

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);
   }
}
Copy after login

Output

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!