Java object, Json, Xml conversion tool Jackson is used

黄舟
Release: 2017-02-22 15:02:36
Original
3679 people have browsed it


It is very common to convert an object into a string in Json format in a Java project. There are many toolkits that can achieve this requirement, such as Gson, JSON-lib , Jackson and so on. This article mainly introduces the use of Jackson. In addition to converting Java objects and Json strings, Jackson can also convert Java objects into Xml format. It is relatively simple to use and is said to be relatively efficient.
For Jackson's jar package, we can download it from the maven resource library: http://www.php.cn/

The required jar package is as follows, just search and download it by name.

Java object, Json, Xml conversion tool Jackson is used

Next to write the test case, we need a java class:

package com.csii.jackson.object;
public class Book{    
private String name;    
private int price;    
public String getName() {        
return name;
    }    public void setName(String name) {        
    this.name = name;
    }    public int getPrice() {        
    return price;
    }    public void setPrice(int price) {        
    this.price = price;
    }    public Book() {

    }    public Book(String name,int price) {        
    this.name = name;        
    this.price = price;
    } 
    @Override    
    public String toString() { 
        return "name:" + name +"; price:" + price;
    }

}
Copy after login
Copy after login

1. Convert the Java object to a Json string:

    @Test    public void testGenJson()
    {
        ObjectMapper objMapper = new ObjectMapper();
        Book book = new Book("Think in Java",100);        try {
            jsonGen = objMapper.getJsonFactory().createJsonGenerator(System.out,JsonEncoding.UTF8);
            jsonGen.writeObject(book);
        } catch (IOException e) { 
            e.printStackTrace();
        } 
    }
Copy after login

Run the test method, console output:

{"name":"Think in Java","price":100}
Copy after login
Copy after login

2. Convert the Json string to a Java object:

    /*
     * Json转Java对象
     */
    @Test    public void testGenObjByJson()
    {
        ObjectMapper objMapper = new ObjectMapper();
        String json = "{\"name\":\"Think in Java\",\"price\":100}"; 
        try {
            Book book = objMapper.readValue(json, Book.class);
            System.out.println(book);
        } catch (IOException e) { 
            e.printStackTrace();
        }  
    }
Copy after login
Copy after login

Since we have rewritten the toString method of the Book class, run the test method, Console output:

name:Think in Java; price:100
Copy after login
Copy after login
Copy after login
Copy after login

3. Convert Java object to Xml format:

     /*
     * Java对象转xml
     */
    @Test    public void testGenXml()
    {
        XmlMapper xmlMapper = new XmlMapper();

        Book book = new Book("Think in Java",100);        try {
            String xmlStr =  xmlMapper.writeValueAsString(book);
            System.out.println(xmlStr);
        } catch (JsonProcessingException e) { 
            e.printStackTrace();
        }
    }
Copy after login
Copy after login

Run the test method, console output:

<Book xmlns=""><name>Think in Java</name><price>100</price></Book>
Copy after login
Copy after login

4. Convert xml format string Convert to Java object:

    /*
     * xml转Java对象
     */
    @Test    public void testGenObjByXml()
    {
        XmlMapper xmlMapper = new XmlMapper();
        String xmlStr = "<Book><name>Think in Java</name><price>100</price></Book>"; 
        try {
            Book book = xmlMapper.readValue(xmlStr, Book.class);
            System.out.println(book);
        } catch (IOException e) {            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
Copy after login
Copy after login

Output content:

name:Think in Java; price:100
Copy after login
Copy after login
Copy after login
Copy after login

Complete test case code:

package com.csii.jackson.test;
import java.io.IOException;
import org.junit.Test;
import com.csii.jackson.object.Book;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
@SuppressWarnings("deprecation")
public class JsonTest { 
    private JsonGenerator jsonGen = null;
    /*
     * Java对象转 Json
     */
    @Test
    public void testGenJson()
    {
        ObjectMapper objMapper = new ObjectMapper();
        Book book = new Book("Think in Java",100);
        try {
            jsonGen = objMapper.getJsonFactory().createJsonGenerator(System.out,JsonEncoding.UTF8);
            jsonGen.writeObject(book);
        } catch (IOException e) { 
            e.printStackTrace();
        } 
    }    /*
     * Json转Java对象
     */
    @Test
    public void testGenObjByJson()
    {
        ObjectMapper objMapper = new ObjectMapper();
        String json = "{\"name\":\"Think in Java\",\"price\":100}"; 
        try {
            Book book = objMapper.readValue(json, Book.class);
            System.out.println(book);
        } catch (IOException e) { 
            e.printStackTrace();
        }  
    }    /*
     * Java对象转xml
     */
    @Test
    public void testGenXml()
    {
        XmlMapper xmlMapper = new XmlMapper();

        Book book = new Book("Think in Java",100);
        try {
            String xmlStr =  xmlMapper.writeValueAsString(book);
            System.out.println(xmlStr);
        } catch (JsonProcessingException e) { 
            e.printStackTrace();
        }
    }    /*
     * xml转Java对象
     */
    @Test
    public void testGenObjByXml()
    {
        XmlMapper xmlMapper = new XmlMapper();
        String xmlStr = "<Book><name>Think in Java</name><price>100</price></Book>"; 
        try {
            Book book = xmlMapper.readValue(xmlStr, Book.class);
            System.out.println(book);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
Copy after login
Copy after login

Convert an object into a Json format string in a Java project It is very common, and there are many toolkits that can meet this requirement, such as Gson, JSON-lib, Jackson, etc. This article mainly introduces the use of Jackson. In addition to converting Java objects and Json strings, Jackson can also convert Java objects into Xml format. It is relatively simple to use and is said to be relatively efficient.
For Jackson's jar package, we can download it from the maven resource library: http://www.php.cn/

The required jar package is as follows, just search and download it by name.

Java object, Json, Xml conversion tool Jackson is used

Next to write the test case, we need a java class:

package com.csii.jackson.object;
public class Book{    
private String name;    
private int price;    
public String getName() {        
return name;
    }    public void setName(String name) {        
    this.name = name;
    }    public int getPrice() {        
    return price;
    }    public void setPrice(int price) {        
    this.price = price;
    }    public Book() {

    }    public Book(String name,int price) {        
    this.name = name;        
    this.price = price;
    } 
    @Override    
    public String toString() { 
        return "name:" + name +"; price:" + price;
    }

}
Copy after login
Copy after login

1. Convert the Java object to a Json string:

    @Test    public void testGenJson()
    {
        ObjectMapper objMapper = new ObjectMapper();
        Book book = new Book("Think in Java",100);        try {
            jsonGen = objMapper.getJsonFactory().createJsonGenerator(System.out,JsonEncoding.UTF8);
            jsonGen.writeObject(book);
        } catch (IOException e) { 
            e.printStackTrace();
        } 
    }
Copy after login

Run the test method, console output:

{"name":"Think in Java","price":100}
Copy after login
Copy after login

2. Convert the Json string to a Java object:

    /*
     * Json转Java对象
     */
    @Test    public void testGenObjByJson()
    {
        ObjectMapper objMapper = new ObjectMapper();
        String json = "{\"name\":\"Think in Java\",\"price\":100}"; 
        try {
            Book book = objMapper.readValue(json, Book.class);
            System.out.println(book);
        } catch (IOException e) { 
            e.printStackTrace();
        }  
    }
Copy after login
Copy after login

Since we have rewritten the toString method of the Book class, run the test method, Console output:

name:Think in Java; price:100
Copy after login
Copy after login
Copy after login
Copy after login

3. Convert Java object to Xml format:

     /*
     * Java对象转xml
     */
    @Test    public void testGenXml()
    {
        XmlMapper xmlMapper = new XmlMapper();

        Book book = new Book("Think in Java",100);        try {
            String xmlStr =  xmlMapper.writeValueAsString(book);
            System.out.println(xmlStr);
        } catch (JsonProcessingException e) { 
            e.printStackTrace();
        }
    }
Copy after login
Copy after login

Run the test method, console output:

<Book xmlns=""><name>Think in Java</name><price>100</price></Book>
Copy after login
Copy after login

4. Convert xml format string Convert to Java object:

    /*
     * xml转Java对象
     */
    @Test    public void testGenObjByXml()
    {
        XmlMapper xmlMapper = new XmlMapper();
        String xmlStr = "<Book><name>Think in Java</name><price>100</price></Book>"; 
        try {
            Book book = xmlMapper.readValue(xmlStr, Book.class);
            System.out.println(book);
        } catch (IOException e) {            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
Copy after login
Copy after login

Output content:

name:Think in Java; price:100
Copy after login
Copy after login
Copy after login
Copy after login

Complete test case code:

package com.csii.jackson.test;
import java.io.IOException;
import org.junit.Test;
import com.csii.jackson.object.Book;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
@SuppressWarnings("deprecation")
public class JsonTest { 
    private JsonGenerator jsonGen = null;
    /*
     * Java对象转 Json
     */
    @Test
    public void testGenJson()
    {
        ObjectMapper objMapper = new ObjectMapper();
        Book book = new Book("Think in Java",100);
        try {
            jsonGen = objMapper.getJsonFactory().createJsonGenerator(System.out,JsonEncoding.UTF8);
            jsonGen.writeObject(book);
        } catch (IOException e) { 
            e.printStackTrace();
        } 
    }    /*
     * Json转Java对象
     */
    @Test
    public void testGenObjByJson()
    {
        ObjectMapper objMapper = new ObjectMapper();
        String json = "{\"name\":\"Think in Java\",\"price\":100}"; 
        try {
            Book book = objMapper.readValue(json, Book.class);
            System.out.println(book);
        } catch (IOException e) { 
            e.printStackTrace();
        }  
    }    /*
     * Java对象转xml
     */
    @Test
    public void testGenXml()
    {
        XmlMapper xmlMapper = new XmlMapper();

        Book book = new Book("Think in Java",100);
        try {
            String xmlStr =  xmlMapper.writeValueAsString(book);
            System.out.println(xmlStr);
        } catch (JsonProcessingException e) { 
            e.printStackTrace();
        }
    }    /*
     * xml转Java对象
     */
    @Test
    public void testGenObjByXml()
    {
        XmlMapper xmlMapper = new XmlMapper();
        String xmlStr = "<Book><name>Think in Java</name><price>100</price></Book>"; 
        try {
            Book book = xmlMapper.readValue(xmlStr, Book.class);
            System.out.println(book);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
Copy after login
Copy after login

The above is the content used by the Java object, Json, and Xml conversion tool Jackson. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template