Jackson入门

1.下载jar包

http://jackson.codehaus.org/1.7.6/jackson-all-1.7.6.jar

官方示例:

http://wiki.fasterxml.com/JacksonInFiveMinutes

2.测试程序

  建立AccountBean.java

package org.qunar.training.jackson;

/**
 * Created by hao.su on 14-5-11.
 */
public class AccountBean {
    private int id;
    private String name;
    private String email;
    private String address;
    private Birthday birthday;

    @Override
    public String toString() {
        return "AccountBean{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", address='" + address + '\'' +
                ", birthday=" + birthday +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Birthday getBirthday() {
        return birthday;
    }

    public void setBirthday(Birthday birthday) {
        this.birthday = birthday;
    }
}

建立测试类

package org.qunar.training.jackson;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by hao.su on 14-5-11.
 */
public class JacksonTest {
    private JsonGenerator jsonGenerator = null;
    private ObjectMapper mapper = null;
    private AccountBean bean = null;

    @Before
    public void init() {
        bean = new AccountBean();
        bean.setAddress("cd.china");
        bean.setEmail("727913675@qq.com");
        bean.setId(1);
        bean.setName("suhao");
        mapper = new ObjectMapper();
        try {
            jsonGenerator = mapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @After
    public void destory() {
        try {
            if (jsonGenerator != null) {

                jsonGenerator.flush();
            }
            if(!jsonGenerator.isClosed()){
                jsonGenerator.close();
            }
            jsonGenerator = null;
            mapper = null;
            bean  = null;
            System.gc();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将实体对象转化为json
     */
    @Test
    public void writeEntityJSON(){
        try{
            System.out.println("jsonGenerator");
            jsonGenerator.writeObject(bean);
            System.out.println();
            System.out.println("Mapper");
            mapper.writeValue(System.out,bean);

        }catch (Exception e){
            System.out.println(e);
        }
    }

    /***
     * 将Map转换为JSON格式
     */
    @Test
    public void writeMapJSON(){
        try{
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("name",bean.getName());
            map.put("address",bean.getAddress());
            map.put("email",bean.getEmail());
            jsonGenerator.writeObject(map);
            System.out.println();
            mapper.writeValue(System.out,map);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 将list转为json格式
     */
    @Test
    public void writeListJSON(){
        try{
            List<AccountBean> list = new ArrayList<AccountBean>();
            list.add(bean);
            bean = new AccountBean();
            bean.setId(2);
            bean.setName("hao.su");
            bean.setEmail("727913675@qq.com");
            bean.setAddress("tsingdao");
            list.add(bean);
            System.out.println("jsonGenerator");
            jsonGenerator.writeObject(list);
            System.out.println();
            System.out.println("Mapper");
            mapper.writeValue(System.out,list);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    
}

上面分别用了JsonGenerator 的writeObject方法和ObjectMappe的writeValue方法来完成对java对象的转换,二者传递的参数以及构造不同,JsonGenerator的构造依赖于ObjectMapper对象

  ObjectMapper的的writeValue方法可以将一个java对象啊转化为json,第一个参数是一个输出流,转化后可以通过这个流来输出内容,或者是一个File直接将内容输出到File中,也可以接受JsonGenerator,通过JsonGenerator来输出转换后的信息,第二个参数是要被转换的java对象,若果用的三个参数的方法那么第三个参数是config,这个Config可以提供一些转换时的规则。

3.下面介绍一下jackson提供的原生类型

@Test
    public void writeOthersJSON() {
        try {
            String[] arr = {"a", "b", "c"};
            System.out.println("jsonGenerator");
            String str = "hello world jackson!";
            //byte
            jsonGenerator.writeBinary(str.getBytes());
            //boolean
            jsonGenerator.writeBoolean(true);
            //null
            jsonGenerator.writeNull();
            //float
            jsonGenerator.writeNumber(2.2f);
            //char
            jsonGenerator.writeRaw("c");
            //String
            jsonGenerator.writeRaw(str, 5, 10);
            //String
            jsonGenerator.writeRawValue(str, 5, 5);
            //String
            jsonGenerator.writeString(str);
            jsonGenerator.writeTree(JsonNodeFactory.instance.POJONode(str));
            System.out.println();

            jsonGenerator.writeStartObject();//{
            jsonGenerator.writeObjectFieldStart("user");//user:{
            jsonGenerator.writeStringField("name", "jackson");//name:jackson
            jsonGenerator.writeBooleanField("sex", true);//sex:true
            jsonGenerator.writeNumberField("age", 22);//age:22
            jsonGenerator.writeEndObject();//}

            jsonGenerator.writeArrayFieldStart("infos");//infos:[
            jsonGenerator.writeNumber(22);//22
            jsonGenerator.writeString("this is array");//this is array
            jsonGenerator.writeEndArray();//]

            jsonGenerator.writeEndObject();//}


            AccountBean bean = new AccountBean();
            bean.setAddress("address");
            bean.setEmail("email");
            bean.setId(1);
            bean.setName("haha");
            //complex Object
            jsonGenerator.writeStartObject();//{
            jsonGenerator.writeObjectField("user", bean);//user:{bean}
            jsonGenerator.writeObjectField("infos", arr);//infos:[array]
            jsonGenerator.writeEndObject();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

4.将json转化为java对象

@Test
    public void readJson2Entity(){
        String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}";
        try{
            AccountBean accountBean = mapper.readValue(json,AccountBean.class);
            System.out.println(accountBean.getName());
            System.out.println(accountBean);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

输出:
haha
AccountBean{id=1, name='haha', email='email', address='address', birthday=null}

第一个参数就是解析的JSON字符串,第二个参数是即将将这个JSON解析吃什么Java对象,Java对象的类型。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值