Simple JSON Development Guide _java

Source: Internet
Author: User
Tags exception handling prev

Simple JSON is the Java JSON parsing framework that Google developed, based on the Apache protocol.

Json-simple's homepage:http://www.jb51.net/softs/455885.html

The downloaded file is: Json_simple.jar

Example 1: A convenient way to use Jsonvalue

 System.out.println ("=======decode======="); 
    
    String s= "[0,{\" 1\ ": {\" 2\ ": {\" 3\ ": {\" 4\ ": [5,{\ ' 6\ ': 7}]}}}]"; 
    Object Obj=jsonvalue.parse (s); 
    Jsonarray array= (jsonarray) obj; 
    System.out.println ("======the 2nd element of array======"); 
    System.out.println (Array.get (1)); 
    System.out.println (); 
        
    Jsonobject obj2= (Jsonobject) array.get (1); 
    System.out.println ("======field \" 1\ "=========="); 
    System.out.println (Obj2.get ("1"));  
  
        
    S= "{}"; 
    Obj=jsonvalue.parse (s); 
    System.out.println (obj); 
        
    S= "[5,]"; 
    Obj=jsonvalue.parse (s); 
    System.out.println (obj); 
        
    S= "[5,,2]"; 
    Obj=jsonvalue.parse (s); 
    

Jsonobject is inherited from map, and Jsonarray is inherited from list, so you can use Jsonobject and Jsonarray in the standard way of map and list.

Jsonvalue can use arrays or objects.

Example 2: Fast way, using jsonparser

 Jsonparser parser=new Jsonparser (); 
  
  System.out.println ("=======decode======="); 
      
  String s= "[0,{\" 1\ ": {\" 2\ ": {\" 3\ ": {\" 4\ ": [5,{\ ' 6\ ': 7}]}}}]"; 
  Object Obj=parser.parse (s); 
  Jsonarray array= (jsonarray) obj; 
  System.out.println ("======the 2nd element of array======"); 
  System.out.println (Array.get (1)); 
  System.out.println (); 
      
  Jsonobject obj2= (Jsonobject) array.get (1); 
  System.out.println ("======field \" 1\ "=========="); 
  System.out.println (Obj2.get ("1"));  
  
      
  S= "{}"; 
  Obj=parser.parse (s); 
  System.out.println (obj); 
      
  S= "[5,]"; 
  Obj=parser.parse (s); 
  System.out.println (obj); 
      
  S= "[5,,2]"; 
  Obj=parser.parse (s); 
  

You need to catch exceptions using Jsonparser.

Example 3: Exception handling

 String jsontext = "[[null, 123.45, \" A\\tb c\ "]}, true"; 
  Jsonparser parser = new Jsonparser (); 
      
  try{ 
  Parser.parse (jsontext); 
  } 
  catch (ParseException pe) { 
  System.out.println ("Position:" + pe.getposition ()); 
  SYSTEM.OUT.PRINTLN (PE); 
  

Execution results:

Position:25 unexpected token right brace (}) at position 25.

Example 4: Container factory

Use the containerfactory class to create a container factory.

 String Jsontext = "{\ first\": 123, \ "second\": [4, 5, 6], \ "third\": 789} "; 
  Jsonparser parser = new Jsonparser (); Containerfactory containerfactory = new Containerfactory () {public List Creatarraycontainer () {return new Linkedli 
  St (); 
  Public Map Createobjectcontainer () {return new Linkedhashmap (); 
      
  } 
        
  }; 
  try{Map JSON = (map) parser.parse (Jsontext, containerfactory); 
  Iterator iter = Json.entryset (). iterator (); 
  System.out.println ("==iterate result=="); 
   while (Iter.hasnext ()) {Map.entry Entry = (map.entry) iter.next (); 
  System.out.println (Entry.getkey () + "=>" + entry.getvalue ()); 
  } System.out.println ("==tojsonstring () = ="); 
  System.out.println (jsonvalue.tojsonstring (JSON)); 
  catch (ParseException pe) {System.out.println (PE); } 

The results are as follows:

==iterate result== first=>123 second=>[4,5,6] third=>789 ==tojsonstring () = =
 {"I": 123, "second": [ 4,5,6], "third": 789}
If you do not use a container factory, Simple-json defaults to using Jsonobject and Jsonarray.
Example 5: A removable sax content processing
Simplejson recommends a simple, accessible, sax-style content processing to handle text flow, where the user can stay at any point in the logical input stream, then process the other logic before continuing with the previous processing. Do not wait for the whole stream to finish. Here is an example.
Keyfinder.java:
 Class Keyfinder implements contenthandler{private Object value; 
  Private Boolean found = false; 
  Private Boolean end = false; 
  Private String key; 
    
  Private String Matchkey; 
  public void Setmatchkey (String matchkey) {this.matchkey = Matchkey; 
  Public Object GetValue () {return value; 
  public Boolean isend () {return end; 
  } public void Setfound (Boolean found) {this.found = found; 
  public Boolean Isfound () {return found; 
  public void Startjson () throws ParseException, IOException {found = false; 
  end = false; 
  public void Endjson () throws ParseException, IOException {end = true; public boolean primitive (Object value) throws ParseException, IOException {if (key!= null) {if (key.equals) ( 
   Matchkey)) {found = true; 
   This.value = value; 
   key = null; 
   return false; 
  } return true; public Boolean Startarray () throws ParseException, IOException {return true; 
  public Boolean StartObject () throws ParseException, IOException {return true; 
  public boolean startobjectentry (String key) throws ParseException, IOException {this.key = key; 
  return true; 
  public Boolean Endarray () throws ParseException, IOException {return false; 
  public Boolean EndObject () throws ParseException, IOException {return true; 
  public Boolean endobjectentry () throws ParseException, IOException {return true;  } 
 }
Main Logic:
String Jsontext = "{\ first\": 123, \ "second\": [{\ "k1\": {\ "id\": \ "Id1\"}}, 4, 5, 6, {\ "id\": 123}], \ "third\": 789, \ "Id\" : null} ";
 Jsonparser parser =newjsonparser ();
 Keyfinder finder =newkeyfinder ();
 Finder.setmatchkey ("id");
 try{
 while (!finder.isend ()) {
  parser.parse (jsontext, finder,true);
  if (Finder.isfound ()) {
  finder.setfound (false);
  SYSTEM.OUT.PRINTLN ("Found ID:");
  System.out.println (Finder.getvalue ());
 }} catch (ParseException pe) {
 pe.printstacktrace ();
 }
Execution results:
Found ID:
 id1
 found ID:
 123
 found ID:
 NULL
Example 6: The entire object graph, with a sax-style parsing
 Class Transformer implements contenthandler{private Stack valuestack; 
    Public Object GetResult () {if (Valuestack = null | | | valuestack.size () = 0) return null; 
   return Valuestack.peek (); 
    public Boolean Endarray () throws ParseException, IOException {trackBack (); 
   return true; public void Endjson () throws ParseException, IOException {} public boolean endobject () throws 
    tion, IOException {trackBack (); 
   return true; 
    public Boolean endobjectentry () throws ParseException, IOException {Object value = Valuestack.pop (); 
    Object key = Valuestack.pop (); 
    Map parent = (map) valuestack.peek (); 
    Parent.put (key, value); 
   return true; 
     private void TrackBack () {if (Valuestack.size () > 1) {Object value = Valuestack.pop (); 
     Object prev = Valuestack.peek (); 
     if (prev instanceof String) {Valuestack.push (value); 
 } 
    } 
   }   
   private void Consumevalue (Object value) {if (valuestack.size () = 0) Valuestack.push (value); 
     else{Object prev = Valuestack.peek (); 
      if (prev instanceof list) {List array = (list) prev; 
     Array.add (value); 
     } else{Valuestack.push (value); }} public Boolean primitive (Object value) throws ParseException, IOException {Consumevalue (val 
    UE); 
   return true; 
    public Boolean Startarray () throws ParseException, IOException {List array = new Jsonarray (); 
    Consumevalue (array); 
    Valuestack.push (array); 
   return true; 
   public void Startjson () throws ParseException, IOException {valuestack = new Stack (); 
    public Boolean StartObject () throws ParseException, IOException {Map object = new Jsonobject (); 
    Consumevalue (object); 
    Valuestack.push (object); 
   return true; public boolean startobjectentry (String key) throwsParseException, IOException {valuestack.push (key); 
   return true;  } 
    
  }
Main Mode logic:
 String jsonstring = <input JSON text>; 
  Object value = null; 
  Jsonparser parser = new Jsonparser (); 
  Transformer Transformer = new Transformer (); 
    
  Parser.parse (jsonstring, transformer); 
  
Execution results:
String jsonstring =<input JSON text>;
 Object value =null;
 Jsonparser parser =newjsonparser ();
 Value = Parser.parse (jsonstring);
Attention:
Jsonpauser is not thread-safe.

json_encode-the variable with JSON encoding.

Description: String json_encode ($value) that returns the JSON form of value values.

Parameter: The value to be encoded, except for the resource type, can be any data type

The function can only accept UTF-8 encoded data (= character/string type of data)

Return value: The successful encoding returns a string in the form of JSON.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.