Tutorial on using Jackson to convert Java objects to JSON _java

Source: Internet
Author: User
Tags dateformat gettext serialization

One, Getting Started
Jackson has a objectmapper class that is useful for the interchange of Java objects with JSON.
1.JAVA Object Json[json serialization]

Import java.io.IOException; 
Import java.text.ParseException; 
 
Import Java.text.SimpleDateFormat; 
 
Import Com.fasterxml.jackson.databind.ObjectMapper;  public class Jacksondemo {public static void main (string[] args) throws ParseException, IOException {User user = 
    New User ();  
    User.setname ("Wang"); 
    User.setemail ("xiaomin@sina.com"); 
     
    User.setage (20); 
    SimpleDateFormat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd");     
     
    User.setbirthday (Dateformat.parse ("1996-10-01")); 
     /** * Objectmapper is the core of the JSON operation, and all of Jackson's JSON operations are implemented in Objectmapper. 
     * Objectmapper has multiple JSON serialization methods that can save JSON strings in different media, such as file, OutputStream, and so on. 
     * WriteValue (file arg0, Object arg1) turns arg1 into a JSON sequence and saves it to the arg0 file. 
     * WriteValue (OutputStream arg0, Object arg1) turns arg1 into a JSON sequence and saves it to the arg0 output stream. 
     * Writevalueasbytes (Object arg0) turns arg0 into a JSON sequence and outputs the result as a byte array. 
     * Writevalueasstring (Object arg0) turns arg0 into a JSON sequence and outputs the result as a string. * * Objectmapper mapper = new Objectmapper (); User class to JSON//output result: {"name": "Min", "Age": "Birthday": 844099200000, "email": "xiaomin@sina.com"} String JSON = Mapp 
    er.writevalueasstring (user); 
     
    SYSTEM.OUT.PRINTLN (JSON); Java set goto JSON//output result: [{"Name": "Min", "Age": "Birthday": 844099200000, "email": "xiaomin@sina.com"}] List<user&gt ; 
    Users = new arraylist<user> (); 
    Users.add (user); 
    String jsonlist = mapper.writevalueasstring (users); 
  System.out.println (jsonlist); 

 } 
}

2.JSON turn Java class [JSON deserialization]

Import java.io.IOException; 
Import java.text.ParseException; 
Import Com.fasterxml.jackson.databind.ObjectMapper; 
 
public class Jacksondemo {public 
  static void Main (string[] args) throws ParseException, IOException { 
    String JSON = "{\" name\ ": \" Wang ", \" age\ ": 20,\" birthday\ ": 844099200000,\" email\ ": \" Xiaomin@sina.com\ "}"; 
     
    /** 
     * Objectmapper supports JSON deserialization of data from byte[], File, InputStream, strings, and so on. 
     */ 
    Objectmapper mapper = new Objectmapper (); 
    User user = Mapper.readvalue (JSON, user.class); 
    SYSTEM.OUT.PRINTLN (user); 
  } 
 


Second, Jackson support 3 ways to use:
1, Data Binding: The most convenient to use.
(1) Full Data Binding:

private static final String model_binding = "{\ name\": \ "name1\", \ "type\": 1} "; 
  public void Fulldatabinding () throws exception{ 
    objectmapper mapper = new Objectmapper (); 
    Model user = Mapper.readvalue (model_binding, Model.class);//readvalue to an entity class. 
    System.out.println (User.getname ()); 
    System.out.println (User.gettype ()); 
  } 

Model class:

private static class model{ 
    private String name; 
    private int type; 
     
    Public String GetName () {return 
      name; 
    } 
    public void SetName (String name) { 
      this.name = name; 
    } 
    public int GetType () {return 
      type; 
    } 
    public void SetType (int type) { 
      this.type = type; 
    } 
  } 

(2) Raw Data Binding:

/** 
  Concrete Java types that Jackson would use for simple data binding are: 
  JSON type    java type 
  object     linkedhashmap<string,object> 
  Array      arraylist<object> 
  string     string number 
  (no Fraction) Integer, Long or BigInteger (smallest applicable) number 
  (fraction)  Double (configurable to use BigDecimal) 
  true|false   Boolean 
  null      null 
  * 
  /public void rawdatabinding () throws exception{ 
    Objectmapper mapper = new Objectmapper (); 
    HashMap map = Mapper.readvalue (model_binding,hashmap.class);//readvalue to an original data type. 
    System.out.println (Map.get ("name")); 
    System.out.println (Map.get ("type")); 
  } 

(3) Generic Data Binding:

private static final String generic_binding = "{\ key1\": {\ "name\": \ "name2\", \ "type\": 2},\ "key2\": {\ "name\": \ "name3\ ", \" Type\ ": 3}}"; 
  public void Genericdatabinding () throws exception{ 
    objectmapper mapper = new Objectmapper (); 
    hashmap<string,model> Modelmap = Mapper.readvalue (Generic_binding,new typereference 
 

2, Tree Model: the most flexible.

private static final String tree_model_binding = "{\ treekey1\": \ "treevalue1\", \ "treekey2\": \ "treevalue2\", \ " 
  Children\ ": [{\" childkey1\ ": \" Childkey1\ "}]}"; 
    public void Treemodelbinding () throws exception{objectmapper mapper = new Objectmapper (); 
    Jsonnode RootNode = Mapper.readtree (tree_model_binding); 
    Path is the same as get, but returns missing node instead of NULL when the node is not found. String Treekey2value = Rootnode.path ("Treekey2"). Gettextvalue ()//System.out.println ("Treekey2value:" + treekey2val 
    UE); 
    Jsonnode Childrennode = Rootnode.path ("Children"); 
    String childkey1value = childrennode.get (0). Path ("Childkey1"). Gettextvalue (); 
     
    System.out.println ("Childkey1value:" +childkey1value); 
    Create root node Objectnode root = Mapper.createobjectnode (); 
    Create child nodes 1 Objectnode node1 = Mapper.createobjectnode (); 
    Node1.put ("Nodekey1", 1); 
    Node1.put ("Nodekey2", 2); 
    Binding child nodes 1 root.put ("Children", node1); Array node Arraynode Arraynode = Mapper.createarraynodE (); 
    Arraynode.add (Node1); 
    Arraynode.add (1); 
    Binding array Node Root.put ("Arraynode", Arraynode); 
    JSON reads to the tree node Jsonnode valuetotreenode = Mapper.valuetotree (tree_model_binding); 
    Bind JSON node Root.put ("Valuetotreenode", Valuetotreenode); 
    JSON binds to the JSON node object Jsonnode bindjsonnode = Mapper.readvalue (generic_binding, jsonnode.class);//bind JSON to the JSON node object. 
    Bind JSON node Root.put ("Bindjsonnode", Bindjsonnode); 
  System.out.println (mapper.writevalueasstring (root)); 
 }

3, streaming API: Best performance.
 
for performance-demanding programs, it is recommended that you use a streaming API, otherwise use jsonfactory, either for creating Jsongenerator or Jsonparser.

Package Com.jingshou.jackson; 
Import Java.io.File; 
 
Import java.io.IOException; 
Import com.fasterxml.jackson.core.JsonEncoding; 
Import Com.fasterxml.jackson.core.JsonFactory; 
Import Com.fasterxml.jackson.core.JsonGenerator; 
Import Com.fasterxml.jackson.core.JsonParser; 
 
Import Com.fasterxml.jackson.core.JsonToken; public class JacksonTest6 {public static void main (string[] args) throws IOException {Jsonfactory jfactory = n 
      
    EW jsonfactory (); /*** write to file ***/jsongenerator jgenerator = jfactory.creategenerator (new file ("C:\\user.json"), JSON 
    ENCODING.UTF8); Jgenerator.writestartobject ();  {Jgenerator.writestringfield ("name", "Mkyong");//"name": "Mkyong" Jgenerator.writenumberfield ("Age", 29); "Age": Jgenerator.writefieldname ("messages"); "Messages": Jgenerator.writestartarray (); [Jgenerator.writestring ("MSG 1");//"MSG 1" jgenerator.writestring ("MSG 2");//"MsG 2 "Jgenerator.writestring (" MSG 3 "); "MSG 3" Jgenerator.writeendarray (); ] Jgenerator.writeendobject (); 
     
    } jgenerator.close (); 
    /*** read from file ***/jsonparser jparser = jfactory.createparser (new file ("C:\\user.json"));  Loop until token equal to '} ' while (Jparser.nexttoken ()!= jsontoken.end_object) {String fieldname = 
      Jparser.getcurrentname (); 
       if ("Name". Equals (fieldname)) {//Current token are ' name ',//move to Next, which is ' name ' ' s value 
       Jparser.nexttoken (); System.out.println (Jparser.gettext ());  
       Display Mkyong} if (' Age '. Equals (fieldname)) {//Current token is ' age ', 
       Move to Next, the which is "name" ' s value jparser.nexttoken (); System.out.println (Jparser.getintvalue ()); Display ' if (' Messages '. Equals (fieldname)) {Jparser.nexttoken ();//CurreNT token is ' [', move next//messages are array, loop until token equal to '] ' while (jparser.nexttok En ()!= Jsontoken.end_array) {//Display MSG1, MSG2, MSG3 System.out.println (jparser.gettext  
    
       ()); 
 
  }} jparser.close (); 
 } 
 
}

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.