jackson 实现 javabean 与 json、xml 互转


  1. jackson 作用 ? 
    可以将 javabean 转换成 json/xml, 也可以将 json/xml 转换成 javabean
  2. jackson 如何使用? 
    主要是通过 ObjectMapper 和 XmlMapper 实现转换

  3. @JsonInclude(JsonInclude.Include.NON_NULL)
    private  DeviceInfo deviceInfo;     null bean对象转为xml string时不转换   或者  
    mapper.setSerializationInclusion(Include.NON_NULL);   null不转换
  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.9.5</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.9.5</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.9.5</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.9.5</version>
</dependency>

Person实体类如下


package com.ps.ukefu.entcunsomer;

/**
 * Created by Admin on 2018/6/11.
 */
import java.util.Arrays;
import java.util.List;

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;
    @JacksonXmlProperty(isAttribute = true)
    private String attribute;

//    @JacksonXmlElementWrapper(localName = "friends",useWrapping = false)
    //生成 <?xml version='1.0' encoding='UTF-8'?><person attribute="post"><name>sarah</name><age>10</age><sex>male</sex><telephone>12345678</telephone><friend>mattew</friend><friend>phoenix</friend></person>

    @JacksonXmlElementWrapper(localName = "friends",useWrapping = true)
    //生成  <?xml version='1.0' encoding='UTF-8'?><person attribute="post"><name>sarah</name><age>10</age><sex>male</sex><telephone>12345678</telephone><friends><friend>mattew</friend><friend>phoenix</friend></friends></person>
    @JacksonXmlProperty(localName = "friend")
    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 String getAttribute() {
        return attribute;
    }

    public void setAttribute(String attribute) {
        this.attribute = attribute;
    }

    /**
     *
     */
    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 com.ps.ukefu.entcunsomer;

/**
 * Author:ZhuShangJin
 * Date:2018/6/11
 */
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 com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
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;

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");
        person.setAttribute("post");
        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","attribute":"post","friends":["mattew","phoenix"]}
    }

    /**
     * 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{

        XmlMapper xmlmapper = new XmlMapper();
        xmlmapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
        // java bean to xml
        String xml = xmlmapper.writeValueAsString(person);

        System.out.println("xml:" + xml);
        // xml:<?xml version='1.0' encoding='UTF-8'?><person attribute="post"><name>sarah</name><age>10</age><sex>male</sex><telephone>12345678</telephone><friends><friend>mattew</friend><friend>phoenix</friend></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{
        //添加  xml头部
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
        // java bean to xml
        String xml = xmlMapper.writeValueAsString(person);

        System.out.println("xml:" + xml);
        // xxml:<?xml version='1.0' encoding='UTF-8'?><person attribute="post"><name>sarah</name><age>10</age><sex>male</sex><telephone>12345678</telephone><friends><friend>mattew</friend><friend>phoenix</friend></friends></person>
    }

    /**
     * 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,
        }
    }

}

猜你喜欢

转载自blog.csdn.net/zsj777/article/details/80648211