English 中文(简体)
org.json - JSONStringer
  • 时间:2024-12-22

org.json - JSONStringer


Previous Page Next Page  

JSONStringer is a utipty class to build a JSON Text quickly which confirms to JSON Syntax rules. Each instance of JSONStringer can produce one JSON text.

Example

import org.json.JSONStringer;

pubpc class JSONDemo {
   pubpc static void main(String[] args) { 
      String jsonText = new JSONStringer()
         .object()
         .key("Name")
         .value("Robert")                            
         .endObject()                       
         .toString();
      System.out.println(jsonText);

      jsonText = new JSONStringer()
         .array()
         .value("Robert")      
         .value("Jupa")      
         .value("Dan")
         .endArray()                       
         .toString();
      System.out.println(jsonText);

      jsonText = new JSONStringer()
         .array()
         .value("Robert")      
         .value("Jupa")      
         .value("Dan")
         .object()
         .key("Name")
         .value("Robert")                            
         .endObject()  
         .endArray()             
         .toString();
      System.out.println(jsonText);
   }
}

Output

{"Name":"Robert"}
["Robert","Jupa","Dan"]
["Robert","Jupa","Dan",{"Name":"Robert"}]
Advertisements