The use of the streaming API in the Jackson Library for parsing Java _java

Source: Internet
Author: User
Tags gettext readable static class

The streaming API reads and writes JSON-content discrete events. Jsonparser reads the data, while the Jsongenerator writes the data. It is the most effective of the three, the lowest cost and the fastest read/write operation. It is similar to the XML Stax parser.

In this article, we'll show you how to read and write JSON data using the Jackson streaming API. Streaming API work using JSON for every detail is to be handled with care. The following examples will use two classes:
Jsongenerator Class--writes the JSON string.
Songenerator is the base class that defines the JSON content written by the public API. Creates an instance using the factory method of the Jsonfactory instance.

class declaration
The following is a declaration of the Org.codehaus.jackson.JsonGenerator class:

Public abstract class Jsongenerator
  extends Object
   implements Closeable

Nested classes

S.N. Class and Description
1 The static class jsongenerator.feature//enumeration defines all the togglable features of the generator.

Field
Protected Prettyprinter _cfgprettyprinter-Object processing is fairly printed (usually redundant whitespace, making the result more readable) when output.

Constructors

S.N. Class and Description
1 Default Constructor

Jsonparser Class--parses the JSON string.
Jsonparser is the base class that defines the JSON content that the public API uses to read. Creates an instance using the factory method of the Jsonfactory instance.

class declaration
The following is a declaration of the Org.codehaus.jackson.JsonParser class:

Public abstract class Jsonparser
  extends Object
   implements Closeable, versioned

Nested classes

S.N. Class and Description
1 The static class Jsonparser.feature//enumeration defines all togglable functions of the parser.
2 The static class Jsonparser.numbertype//enumeration can be used for the possible "local" (best) types of numbers.

Field

    • Protected Prettyprinter _cfgprettyprinter-Object handling fairly prints (usually extra whitespace, making the result more readable) output.
    • Protected Jsontoken _currtoken-retrieves the last token (if any) through Nexttoken ().
    • protected int _features-bit flag indicating that it is enabled for jsonparser.features composition.
    • Protected Jsontoken _lastclearedtoken-final purge token if any: Clearcurrenttoken () is invoked when the value is valid.

Constructors

S.N. Class and Description
1 protected Jsonparser ()//default constructor
2 protected Jsonparser (int features)

Methods of inheritance
This class inherits the following class methods:

Copy Code code as follows:

Java.lang.Object


writing JSON using Jsongenerator
The use of Jsongenerator is very simple. First use the Jsonfactory.createjsongenerator () method to create a jsongenerator and write each JSON value using the write*** () method.

Jsonfactory jasonfactory = new Jsonfactory ();
Jsongenerator jsongenerator = jasonfactory.createjsongenerator (new File (
  "Student.json"), Jsonencoding.utf8);
{
jsongenerator.writestartobject ();
"Name": "Mahesh Kumar"
Jsongenerator.writestringfield ("name", "Mahesh Kumar"); 

Let's look at the jsongenerator operation. Create a Java class file named Jacksontester in the directory c:\>jackson_workspace.

File:JacksonTester.java

Import Java.io.File;
Import java.io.IOException;

Import Java.util.Map;
Import org.codehaus.jackson.JsonEncoding;
Import Org.codehaus.jackson.JsonFactory;
Import Org.codehaus.jackson.JsonGenerator;
Import org.codehaus.jackson.JsonParseException;
Import org.codehaus.jackson.map.JsonMappingException;

Import Org.codehaus.jackson.map.ObjectMapper;
   public class Jacksontester {public static void main (String args[]) {Jacksontester tester = new Jacksontester ();

     try {jsonfactory jasonfactory = new Jsonfactory ();
     Jsongenerator jsongenerator = jasonfactory.createjsongenerator (New File ("Student.json"), Jsonencoding.utf8);
     {Jsongenerator.writestartobject (); 
     "Name": "Mahesh Kumar" Jsongenerator.writestringfield ("name", "Mahesh Kumar");
     "Age": Jsongenerator.writenumberfield ("Age", 21); 
     "Verified": false Jsongenerator.writebooleanfield ("verified", false); "Marks": [JSONGENERATOR.W]Ritefieldname ("Marks"); 
     [Jsongenerator.writestartarray (); 
     Jsongenerator.writenumber (100); 
     Jsongenerator.writenumber (90); 
     Jsongenerator.writenumber (85); 
     ] Jsongenerator.writeendarray (); 
     } jsongenerator.writeendobject ();     

     Jsongenerator.close (); Result Student.json//{//' name ': "Mahesh Kumar",//"Age": ",//" verified ": false,//" Ma
     Rks ": [100,90,85]//} objectmapper mapper = new Objectmapper ();

     map<string,object> Datamap = Mapper.readvalue (New File ("Student.json"), Map.class);
     System.out.println (Datamap.get ("name"));
     System.out.println (Datamap.get ("Age"));
     System.out.println (Datamap.get ("verified"));
   System.out.println (Datamap.get ("Marks"));
   catch (Jsonparseexception e) {e.printstacktrace ();
   catch (Jsonmappingexception e) {e.printstacktrace ();
catch (IOException e) {e.printstacktrace ();   }
  }
}

 

Validation results

Use Javac to compile the following classes:

Copy Code code as follows:

C:\jackson_workspace>javac Jacksontester.java


Now run Jacksontester See the results:

Copy Code code as follows:

C:\jackson_workspace>java Jacksontester



Validating output

Mahesh Kumar
false
[100, 90, 85]

Using Jsonparser to read JSON
the use of Jsonparser is very simple. First use the Jsonfactory.createjsonparser () method to create the Jsonparser and use its nexttoken () method to read each JSON string as a token. Check each token and the corresponding process.

Jsonfactory jasonfactory = new Jsonfactory ();
Jjsonparser Jsonparser = Jasonfactory.createjsonparser (New File ("Student.json"));
while (Jsonparser.nexttoken ()!= jsontoken.end_object) {
  //get the current token
  String fieldname = Jsonparser.getcurrentname ();
  if ("Name". Equals (fieldname)) {
   //move to next token
   jsonparser.nexttoken ();
   System.out.println (Jsonparser.gettext ());     
  }

Let's look at the jsonparser operation. Create a c:\>jackson_workspace named Jacksontester in the Java class in the folder.

File: Jacksontester.java

Import Java.io.File;

Import java.io.IOException;
Import org.codehaus.jackson.JsonEncoding;
Import Org.codehaus.jackson.JsonFactory;
Import Org.codehaus.jackson.JsonGenerator;
Import org.codehaus.jackson.JsonParseException;
Import Org.codehaus.jackson.JsonParser;
Import Org.codehaus.jackson.JsonToken;

Import org.codehaus.jackson.map.JsonMappingException;
   public class Jacksontester {public static void main (String args[]) {Jacksontester tester = new Jacksontester ();

     try {jsonfactory jasonfactory = new Jsonfactory ();
     Jsongenerator jsongenerator = jasonfactory.createjsongenerator (New File ("Student.json"), Jsonencoding.utf8);
     Jsongenerator.writestartobject (); 
     Jsongenerator.writestringfield ("name", "Mahesh Kumar");
     Jsongenerator.writenumberfield ("Age", 21); 
     Jsongenerator.writebooleanfield ("verified", false); 
     Jsongenerator.writefieldname ("Marks"); Jsongenerator.writestartarray (); 
   [Jsongenerator.writenumber (100);  Jsongenerator.writenumber (90); 
     Jsongenerator.writenumber (85); 
     Jsongenerator.writeendarray (); 
     Jsongenerator.writeendobject ();     

     Jsongenerator.close (); Result Student.json//{//' name ': "Mahesh Kumar",//"Age": ",//" verified ": false,//" Ma
     Rks ": [100,90,85]//} Jsonparser Jsonparser = Jasonfactory.createjsonparser (New File (" Student.json ")); while (Jsonparser.nexttoken ()!= jsontoken.end_object) {//get The current token String fieldname = Jsonparser
      . Getcurrentname ();
        if ("Name". Equals (fieldname)) {//move to Next token jsonparser.nexttoken ();     
      System.out.println (Jsonparser.gettext ());
        } if (' Age '. Equals (fieldname)) {//move to Next token jsonparser.nexttoken ();     
      System.out.println (Jsonparser.getnumbervalue ());
     } if ("Verified". Equals (fieldname)) {//move to Next token jsonparser.nexttoken ();   System.out.println (Jsonparser.getbooleanvalue ());
        } if ("Marks". Equals (fieldname)) {//move to [Jsonparser.nexttoken (); Loop till token equal to "'" while (Jsonparser.nexttoken ()!= jsontoken.end_array) {System.out.printl 
        N (Jsonparser.getnumbervalue ());
   catch (Jsonparseexception e) {e.printstacktrace ()}}};
   catch (Jsonmappingexception e) {e.printstacktrace ();
   catch (IOException e) {e.printstacktrace ();

 }
  }
}

Validation results

Compilation uses Javac to compile the following classes:

Copy Code code as follows:

C:\jackson_workspace>javac Jacksontester.java


Now run Jacksontester see the results as follows:

Copy Code code as follows:

C:\jackson_workspace>java Jacksontester


Validating output

Mahesh Kumar
false
[100, 90, 85]

Related Article

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.