jackson 实现 javabean 与 json、xml 互转

  1. jackson 是什么?
    jackson 是一个 java类库,实际上是一个转换器。
  2. jackson 作用 ?
    可以将 javabean 转换成 json/xml, 也可以将 json/xml 转换成 javabean
  3. jackson 如何使用?
    主要是通过 ObjectMapper 和 XmlMapper 实现转换

  4. jackson 导包如下:


        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.5.4version>
        dependency>

        
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-coreartifactId>
            <version>2.5.4version>
        dependency>

        
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-annotationsartifactId>
            <version>2.5.0version>
        dependency>

        
        <dependency>
            <groupId>com.fasterxml.jackson.dataformatgroupId>
            <artifactId>jackson-dataformat-xmlartifactId>
            <version>2.5.4version>
        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 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 getFriends() {
        return friends;
    }
    /**
     * @param friends the friends to set
     */
    public void setFriends(List 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 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 friends = new ArrayList();
        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: sarah10male12345678mattewphoenix

        // 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:sarah10male12345678mattewphoenix

        //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 map = new HashMap();
        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> iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            Entry entry = (Entry)iterator.next();
            System.out.print(entry.getKey() + ":" + entry.getValue() + ", ");
            // friends:[mattew, phoenix], name:sarah, age:10, 
        }
    }

}
  1. 源码 github 下载地址如下:
    (https://github.com/xiaoyugelicai/TestJackson.git)

你可能感兴趣的:(对接接口相关技能)