欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用Jackson来实现Java对象与JSON的相互转换的教程

程序员文章站 2024-03-08 09:49:40
一、入门 jackson中有个objectmapper类很是实用,用于java对象与json的互换。 1.java对象转json[json序列化] impor...

一、入门
jackson中有个objectmapper类很是实用,用于java对象与json的互换。
1.java对象转json[json序列化]

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("小民");  
    user.setemail("xiaomin@sina.com"); 
    user.setage(20); 
     
    simpledateformat dateformat = new simpledateformat("yyyy-mm-dd"); 
    user.setbirthday(dateformat.parse("1996-10-01"));     
     
    /** 
     * objectmapper是json操作的核心,jackson的所有json操作都是在objectmapper中实现。 
     * objectmapper有多个json序列化的方法,可以把json字符串保存file、outputstream等不同的介质中。 
     * writevalue(file arg0, object arg1)把arg1转成json序列,并保存到arg0文件中。 
     * writevalue(outputstream arg0, object arg1)把arg1转成json序列,并保存到arg0输出流中。 
     * writevalueasbytes(object arg0)把arg0转成json序列,并把结果输出成字节数组。 
     * writevalueasstring(object arg0)把arg0转成json序列,并把结果输出成字符串。 
     */ 
    objectmapper mapper = new objectmapper(); 
     
    //user类转json 
    //输出结果:{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"} 
    string json = mapper.writevalueasstring(user); 
    system.out.println(json); 
     
    //java集合转json 
    //输出结果:[{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}] 
    list<user> users = new arraylist<user>(); 
    users.add(user); 
    string jsonlist = mapper.writevalueasstring(users); 
    system.out.println(jsonlist); 
  } 
} 

2.json转java类[json反序列化]

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\":\"小民\",\"age\":20,\"birthday\":844099200000,\"email\":\"xiaomin@sina.com\"}"; 
     
    /** 
     * objectmapper支持从byte[]、file、inputstream、字符串等数据的json反序列化。 
     */ 
    objectmapper mapper = new objectmapper(); 
    user user = mapper.readvalue(json, user.class); 
    system.out.println(user); 
  } 
} 

 
二、jackson支持3种使用方式:
1、data binding:最方便使用.
(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到一个实体类中. 
    system.out.println(user.getname()); 
    system.out.println(user.gettype()); 
  } 

model类:

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 will 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到一个原始数据类型. 
    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<hashmap<string,model>>(){});//readvalue到一个范型数据中. 
    model model = modelmap.get("key2"); 
    system.out.println(model.getname()); 
    system.out.println(model.gettype()); 
  } 

2、tree model:最灵活。

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与get作用相同,但是当找不到该节点的时候,返回missing node而不是null. 
    string treekey2value = rootnode.path("treekey2").gettextvalue();// 
    system.out.println("treekey2value:" + treekey2value); 
    jsonnode childrennode = rootnode.path("children"); 
    string childkey1value = childrennode.get(0).path("childkey1").gettextvalue(); 
    system.out.println("childkey1value:"+childkey1value); 
     
    //创建根节点 
    objectnode root = mapper.createobjectnode(); 
    //创建子节点1 
    objectnode node1 = mapper.createobjectnode(); 
    node1.put("nodekey1",1); 
    node1.put("nodekey2",2); 
    //绑定子节点1 
    root.put("child",node1); 
    //数组节点 
    arraynode arraynode = mapper.createarraynode(); 
    arraynode.add(node1); 
    arraynode.add(1); 
    //绑定数组节点 
    root.put("arraynode", arraynode); 
    //json读到树节点 
    jsonnode valuetotreenode = mapper.valuetotree(tree_model_binding); 
    //绑定json节点 
    root.put("valuetotreenode",valuetotreenode); 
    //json绑定到json节点对象 
    jsonnode bindjsonnode = mapper.readvalue(generic_binding, jsonnode.class);//绑定json到json节点对象. 
    //绑定json节点 
    root.put("bindjsonnode",bindjsonnode); 
    system.out.println(mapper.writevalueasstring(root)); 
  } 

3、streaming api:最佳性能。
 
对于性能要求高的程序,推荐使用流api,否则使用其他方法
不管是创建jsongenerator还是jsonparser,都是使用jsonfactory。

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 = new jsonfactory(); 
      
    /*** write to file ***/ 
    jsongenerator jgenerator = jfactory.creategenerator(new file( 
        "c:\\user.json"), jsonencoding.utf8); 
    jgenerator.writestartobject(); // { 
    
    jgenerator.writestringfield("name", "mkyong"); // "name" : "mkyong" 
    jgenerator.writenumberfield("age", 29); // "age" : 29 
    
    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 is "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, which is "name"'s value 
       jparser.nexttoken(); 
       system.out.println(jparser.getintvalue()); // display 29 
    
      } 
    
      if ("messages".equals(fieldname)) { 
    
       jparser.nexttoken(); // current token is "[", move next 
    
       // messages is array, loop until token equal to "]" 
       while (jparser.nexttoken() != jsontoken.end_array) { 
    
             // display msg1, msg2, msg3 
         system.out.println(jparser.gettext());  
    
       } 
    
      } 
    
     } 
     jparser.close(); 
 
  } 
 
}