jackson 实现 javabean 与 json、xml 互转

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_23039605/article/details/71080190
  1. jackson 是什么?
    jackson 是一个 java类库,实际上是一个转换器。
  2. jackson 作用 ?
    可以将 javabean 转换成 json/xml, 也可以将 json/xml 转换成 javabean
  3. jackson 如何使用?
    主要是通过 ObjectMapper 和 XmlMapper 实现转换

  4. jackson 导包如下:

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.5.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.5.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.5.4</version>
        </dependency>
  1. Person 实体类代码如下:
package vo;

import java.util.List;
import org.apache.catalina.tribes.util.Arrays;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

@JacksonXmlRootElement(localName="person")
public class Person {

    private String name;
    private Integer age;
    private String sex;
    private String telephone;

    @JacksonXmlElementWrapper(localName="friends")
    @JacksonXmlProperty(localName="string")
    private List<String> friends;
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * @return the age
     */
    public Integer getAge() {
        return age;
    }
    /**
     * @param age the age to set
     */
    public void setAge(Integer age) {
        this.age = age;
    }
    /**
     * @return the sex
     */
    public String getSex() {
        return sex;
    }
    /**
     * @param sex the sex to set
     */
    public void setSex(String sex) {
        this.sex = sex;
    }
    /**
     * @return the telephone
     */
    public String getTelephone() {
        return telephone;
    }
    /**
     * @param telephone the telephone to set
     */
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    /**
     * @return the friends
     */
    public List<String> getFriends() {
        return friends;
    }
    /**
     * @param friends the friends to set
     */
    public void setFriends(List<String> friends) {
        this.friends = friends;
    }
    /**
     * @param name
     * @param age
     * @param sex
     * @param telephone
     * @param friends
     */
    public Person(String name, Integer age, String sex, String telephone, List<String> friends) {
        super();
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.telephone = telephone;
        this.friends = friends;
    }
    /**
     * 
     */
    public Person() {
        super();
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", sex=" + sex + ", telephone=" + telephone + ", friends="
                + Arrays.toString(friends.toArray()) + "]";
    }


}
  1. 具体测试代码如下:
package testJackson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Before;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.thoughtworks.xstream.XStream;

import vo.Person;

/**
 * This class was used to test jackson converter, jackson was used to convert json or xml to javabean or convert javabean to json or xml.
 * @author hualei
 * @date Apr 28, 2017 4:14:53 PM
 * 
 */
public class TestJackson {

    /**
     * convert json to javabean or javabean to json.
     */
    private ObjectMapper objectMapper = new ObjectMapper();
    /**
     * convert xml to javabean or javabean to xml.
     */
    private XmlMapper xmlMapper = new XmlMapper();

    private Person person;

    @Before
    public void init(){
        person = new Person();
        person.setName("sarah");
        person.setAge(10);
        person.setSex("male");
        person.setTelephone("12345678");
        List<String> friends = new ArrayList<String>();
        friends.add("mattew");
        friends.add("phoenix");
//      String[] friends = new String[2];
//      friends[0] = "mattew";
//      friends[1] = "phoenix";
        person.setFriends(friends);
    }

    /**
     * convert java bean to json.
     * @throws IOException 
     */
    @Test
    public void testJavabeanToJSON() throws IOException{
        // java bean to json
        String json = objectMapper.writeValueAsString(person);
        System.out.println("json:" + json);
        //json:{"name":"sarah","age":10,"sex":"male","telephone":"12345678","friends":["mattew","phoenix"]}

        //JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
        //jsonGenerator.writeObject(person);
    }

    /**
     * convert json to java bean.
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     */
    @Test
    public void testJsonToJavabean() throws JsonParseException, JsonMappingException, IOException{
        String json = "{\"name\":\"sarah\",\"age\":10,\"sex\":\"male\",\"telephone\":\"12345678\",\"friends\":[\"mattew\",\"phoenix\"]}";
        // json to java bean
        Person person = objectMapper.readValue(json, Person.class);
        System.out.println("person:" + person);
        // person:Person [name=sarah, age=10, sex=male, telephone=12345678, friends={mattew, phoenix}]
    }

    /**
     * convert xml to javabean.
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     */
    @Test
    public void testXmlToJavabean() throws JsonParseException, JsonMappingException, IOException{
        XStream xstream = new XStream();
        xstream.alias("person", Person.class);
        String xml = xstream.toXML(person);
        System.out.println("xml:" + xml);
        // xml: <person><name>sarah</name><age>10</age><sex>male</sex><telephone>12345678</telephone><friends><string>mattew</string><string>phoenix</string></friends></person>

        // xml to java bean
        Person generatePerson = xmlMapper.readValue(xml, Person.class);
        System.out.println("person:" + generatePerson.toString());
        // person:Person [name=sarah, age=10, sex=male, telephone=12345678, friends={mattew, phoenix}]
    }

    /**
     * convert javabean to xml.
     * @throws IOException
     */
    @Test
    public void testJavabeanToXml() throws IOException{
        // java bean to xml
        String xml = xmlMapper.writeValueAsString(person);
        System.out.println("xml:" + xml);
        // xml:<person xmlns=""><name>sarah</name><age>10</age><sex>male</sex><telephone>12345678</telephone><friends><string>mattew</string><string>phoenix</string></friends></person>

        //String xml = xmlMapper.writer().with(SerializationFeature.WRAP_ROOT_VALUE).withRootName("person").writeValueAsString(person);
        //System.out.println("xml:" + xml);
    }

    /**
     * convert map to json.
     * @throws JsonProcessingException
     */
    @Test
    public void testMapToJSON() throws JsonProcessingException{
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "sarah");
        map.put("age", 10);

        // map to json
        String json = objectMapper.writeValueAsString(map);
        System.out.println("json:" + json);
        // json:{"friends":["mattew","phoenix"],"age":10,"name":"sarah"}
    }

    /**
     * convert json to map.
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Test
    public void testJsonToMap() throws JsonParseException, JsonMappingException, IOException{
        String json = "{\"friends\":[\"mattew\",\"phoenix\"],\"age\":10,\"name\":\"sarah\"}";
        // json to map 
        Map map = objectMapper.readValue(json, HashMap.class);
        Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            Entry<String, Object> entry = (Entry<String, Object>)iterator.next();
            System.out.print(entry.getKey() + ":" + entry.getValue() + ", ");
            // friends:[mattew, phoenix], name:sarah, age:10, 
        }
    }

}
  1. 源码 github 下载地址如下:
    (https://github.com/xiaoyugelicai/TestJackson.git)
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页