JSON 之 jackson 用法


Jackson简单用法一:

importjava.text.SimpleDateFormat; 

importjava.util.ArrayList; 

importjava.util.Date; 

importjava.util.HashMap; 

importjava.util.List; 

importjava.util.Map; 

 

import org.codehaus.jackson.JsonGenerator

importorg.codehaus.jackson.map.DeserializationConfig; 

importorg.codehaus.jackson.map.ObjectMapper; 

import org.codehaus.jackson.map.SerializationConfig

importorg.codehaus.jackson.map.annotate.JsonSerialize.Inclusion; 

importorg.codehaus.jackson.type.TypeReference;

 

import com.fasterxml.jackson.databind.DeserializationFeature;

 

import java.util.Date

 

public classJacksonTest { 

    public staticObjectMapper getDefaultObjectMapper() { 

       ObjectMapper mapper = new ObjectMapper(); 

        //设置将对象转换成JSON字符串时候:包含的属性不能为空或"";   

        //Include.Include.ALWAYS 默认   

        //Include.NON_DEFAULT 属性为默认值不序列化   

        //Include.NON_EMPTY 属性为空(""  或者为 NULL 都不序列化   

        //Include.NON_NULL 属性为NULL 不序列化   

        mapper.setSerializationInclusion(Inclusion.NON_EMPTY); 

       

        //设置将MAP转换为JSON时候只转换值不等于NULL 

        mapper.configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false); 

        mapper.setDateFormat(newSimpleDateFormat("yyyy-MM-ddHH:mm:ss")); 

//     mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true); 

       

        //设置有属性不能映射成PO时不报错 

        mapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES); 

//     mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);  上一条也可以如此设置;

       

        return mapper

    } 

    public static voidmain(String[] args) throws Exception{ 

        //准备数据 

        Name name1 = new Name("zhang","san"); 

        Name name2 = new Name("li","si"); 

        Name name3 = new Name("wang","wu"); 

        Student student1 = newStudent(1,name1,"一班",newDate());   

        Student student2 = newStudent(2,name2,"二班",newDate());   

        Student student3 = newStudent(3,name3,"三班",newDate());   

       List<Student> studentList = new ArrayList<Student>(); 

        studentList.add(student1); 

        studentList.add(student2); 

        studentList.add(student3); 

       Map<String,Student> studentMap = new HashMap<String, Student>(); 

        studentMap.put("1", student1); 

        studentMap.put("2", student2); 

        studentMap.put("3", student3); 

        Student json2object = null

       List<Student> json2list = null

       Map<String,Student> json2map = null

       ObjectMapper mapper = getDefaultObjectMapper(); 

         

        /* Object --> JSON */ 

        String object4json = mapper.writeValueAsString(student1); 

        System.out.println("Object ----> JSON"); 

        System.out.println(object4json); 

        System.out.println("------------------------------------------------------"); 

         

        /* List<Object> --> JSON */ 

        String listforjson = mapper.writeValueAsString(studentList); 

        System.out.println("List<Object> ----> JSON"); 

        System.out.println(listforjson); 

        System.out.println("------------------------------------------------------"); 

         

        /* Map<String,Object> ----> JSON */ 

        String map4json = mapper.writeValueAsString(studentMap); 

        System.out.println("Map<String,Object> ----> JSON"); 

        System.out.println(map4json); 

        System.out.println("------------------------------------------------------"); 

         

        /* JSON --> Object */ 

        json2object = mapper.readValue(object4json,Student.class); 

        System.out.println("JSON ----> Object"); 

        System.out.println(json2object); 

        System.out.println("------------------------------------------------------"); 

        /* JSON --> List<Object> */ 

        json2list = mapper.readValue(listforjson, newTypeReference<List<Student>>() {}); 

        System.out.println("JSON --> List<Object>"); 

        System.out.println(json2list.toString()); 

        System.out.println("------------------------------------------------------"); 

        /* JSON --> Map<String,Object> */ 

        json2map = mapper.readValue(map4json, newTypeReference<Map<String,Student>>() {}); 

        System.out.println("JSON --> Map<String,Object>"); 

        System.out.println(json2map.toString()); 

    } 

 

class Name{ 

    private String firstName

    private String lastName

    publicName(){} 

    publicName(String firstName, String lastName) { 

        this.firstName = firstName

        this.lastName = lastName

    } 

    public StringgetFirstName() { 

        return firstName

    } 

    public voidsetFirstName(String firstName) { 

        this.firstName = firstName

    } 

    public StringgetLastName() { 

        return lastName

    } 

    public voidsetLastName(String lastName) { 

        this.lastName = lastName

    } 

    public StringtoString() { 

        return firstName + " " + lastName

    } 

 

 

 class Student{ 

    private int id

    private Name name

    private String className

    private Date birthDay

    publicStudent(){} 

    publicStudent(int id, Name name, String className, Date birthDay) { 

        super(); 

        this.id = id

        this.name = name

        this.className = className

        this.birthDay = birthDay

    } 

    public int getId(){ 

        return id

    } 

    public void setId(int id) { 

        this.id = id

    } 

    public NamegetName() { 

        return name

    } 

    public voidsetName(Name name) { 

        this.name = name

    } 

    public DategetBirthDay() { 

        return birthDay

    } 

    public voidsetBirthDay(Date birthDay) { 

        this.birthDay = birthDay

    } 

    public StringgetClassName() { 

        return className

    } 

    public voidsetClassName(String className) { 

        this.className = className

    } 

    @Override 

    public StringtoString() { 

        return "Student [birthDay=" + birthDay + ",id=" + id + ", name=" + name + ",classname="+ className + "]"

    } 

 

/* 输出:

 Object ---->JSON

 {"id":1,"name":{"firstName":"zhang","lastName":"san"},"className":"一班","birthDay":"2016-08-2420:20:15"}

 ------------------------------------------------------

 List<Object>----> JSON

 [{"id":1,"name":{"firstName":"zhang","lastName":"san"},"className":"一班","birthDay":"2016-08-2420:20:15"},{"id":2,"name":{"firstName":"li","lastName":"si"},"className":"二班","birthDay":"2016-08-2420:20:15"},{"id":3,"name":{"firstName":"wang","lastName":"wu"},"className":"三班","birthDay":"2016-08-2420:20:15"}]

 ------------------------------------------------------

 Map<String,Object> ----> JSON

 {"3":{"id":3,"name":{"firstName":"wang","lastName":"wu"},"className":"三班","birthDay":"2016-08-2420:20:15"},"2":{"id":2,"name":{"firstName":"li","lastName":"si"},"className":"二班","birthDay":"2016-08-2420:20:15"},"1":{"id":1,"name":{"firstName":"zhang","lastName":"san"},"className":"一班","birthDay":"2016-08-2420:20:15"}}

 ------------------------------------------------------

 JSON ---->Object

 Student[birthDay=Wed Aug 24 20:20:15 CST 2016, id=1, name=zhang san,classname=一班]

 ------------------------------------------------------

 JSON -->List<Object>

 [Student[birthDay=Wed Aug 24 20:20:15 CST 2016, id=1, name=zhang san,classname=一班],Student [birthDay=Wed Aug 24 20:20:15 CST 2016, id=2, name=li si,classname=二班],Student [birthDay=Wed Aug 24 20:20:15 CST 2016, id=3, name=wang wu,classname=三班]]

 ------------------------------------------------------

 JSON -->Map<String,Object>

 {3=Student[birthDay=Wed Aug 24 20:20:15 CST 2016, id=3, name=wang wu,classname=三班],2=Student [birthDay=Wed Aug 24 20:20:15 CST 2016, id=2, name=li si,classname=二班],1=Student [birthDay=Wed Aug 24 20:20:15 CST 2016, id=1, name=zhangsan, classname=一班]}

*/

 

 

 

Jackson简单用法二:

 

 

 

 

importjava.io.File;

importjava.io.IOException;

importjava.io.InputStream;

importjava.io.OutputStream;

importjava.io.Reader;

importjava.io.Writer;

importjava.net.URL;

importjava.text.DateFormat;

importjava.text.SimpleDateFormat;

 

importorg.codehaus.jackson.JsonGenerationException;

importorg.codehaus.jackson.JsonParseException;

importorg.codehaus.jackson.map.DeserializationConfig;

importorg.codehaus.jackson.map.JsonMappingException;

importorg.codehaus.jackson.map.ObjectMapper;

importorg.codehaus.jackson.map.SerializationConfig;

importorg.codehaus.jackson.map.annotate.JsonSerialize;

/*

 * ObjectMapperreadValue() 方法:

<T> T   readValue(byte[]src, Class<T> valueType)

<T> T   readValue(byte[]src, JavaType valueType)

<T> T   readValue(byte[]src, TypeReference valueTypeRef)

<T> T   readValue(Filesrc, Class<T> valueType)

<T> T   readValue(Filesrc, JavaType valueType)

<T> T   readValue(Filesrc, TypeReference valueTypeRef)

<T> T   readValue(InputStreamsrc, Class<T> valueType)

<T> T   readValue(InputStreamsrc, JavaType valueType)

<T> T   readValue(InputStreamsrc, TypeReference valueTypeRef)

<T> T   readValue(JsonNoderoot, Class<T> valueType)

<T> T   readValue(JsonNoderoot, JavaType valueType)

<T> T   readValue(JsonNoderoot, TypeReference valueTypeRef)

<T> T   readValue(JsonParserjp, Class<T> valueType)

<T> T   readValue(Readersrc, Class<T> valueType)

<T> T   readValue(Readersrc, JavaType valueType)

<T> T   readValue(Readersrc, TypeReference valueTypeRef)

<T> T   readValue(Stringcontent, Class<T> valueType)

<T> T   readValue(Stringcontent, JavaType valueType)

<T> T   readValue(Stringcontent, TypeReference valueTypeRef)

 

 

ObjectMapperwriteValue() 方法:

 

void writeValue(File resultFile, Object value)

void    writeValue(JsonGeneratorjgen, Object value)

void    writeValue(JsonGeneratorjgen, Object value, SerializationConfig config)

void    writeValue(OutputStreamout, Object value)

void    writeValue(Writerw, Object value)

byte[]  writeValueAsBytes(Objectvalue)

String  writeValueAsString(Objectvalue)

*/

 

 

public classJsonFormatter {

    private static finalThreadLocal<ObjectMapper> INCLUDE_NULL_MAPPER = new ThreadLocal();

 

    private static finalThreadLocal<ObjectMapper> NOT_INCLUDE_NULL_MAPPER = new ThreadLocal();

 

    private staticObjectMapper getMapper(boolean serializeNull) {

        ThreadLocaltl = serializeNull ? INCLUDE_NULL_MAPPER : NOT_INCLUDE_NULL_MAPPER; //t1是引用变量,指向两者中的一个

        if (null == tl.get()){

            ObjectMappermapper = new ObjectMapper();

           

            mapper.disable(

                    newDeserializationConfig.Feature[] { DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES });

 

            mapper.setDateFormat(newSimpleDateFormat("yyyy-MM-dd"));

            if (!serializeNull){  //不包括null

                mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

                mapper.disable(newSerializationConfig.Feature[] { SerializationConfig.Feature.WRITE_NULL_MAP_VALUES });

            }

 

            tl.set(mapper);

        }

 

        return(ObjectMapper) tl.get();

    }

 

    public static StringtoJsonString(Object obj) throws JsonGenerationException, JsonMappingException,IOException {

        return toJsonString(obj, true);

    }

 

    public static StringtoJsonAsString(Object obj) throws JsonGenerationException, JsonMappingException,IOException {

        return toJsonAsString(obj, true);

    }

 

    public static byte[]toJsonAsBytes(Object obj) throws JsonGenerationException, JsonMappingException,IOException {

        return toJsonAsBytes(obj, true);

    }

 

    public static voidtoJsonToFile(File file, Object obj)

            throwsJsonGenerationException, JsonMappingException, IOException {

        toJsonToFile(file, obj, true);

    }

 

    public static voidtoJsonToOutputStream(OutputStream out, Object obj)

            throwsJsonGenerationException, JsonMappingException, IOException {

        toJsonToOutputStream(out, obj, true);

    }

 

    public static voidtoJsonToWriter(Writer writer, Object obj)

            throwsJsonGenerationException, JsonMappingException, IOException {

        toJsonToWriter(writer, obj, true);

    }

 

    public static<T> T toObject(String json, Class<T> clazz)

            throwsJsonParseException, JsonMappingException, IOException {

        return toObject(json, clazz, true);

    }

 

    public static<T> T toObject(byte[] src, Class<T> clazz)

            throwsJsonParseException, JsonMappingException, IOException {

        return toObject(src, clazz, true);

    }

 

    public static  <T> T toObject(File file,Class<T> clazz)

            throwsJsonParseException, JsonMappingException, IOException {

        return toObject(file, clazz, true);

    }

 

    public static<T> T toObject(InputStream input, Class<T> clazz)

            throwsJsonParseException, JsonMappingException, IOException {

        return toObject(input, clazz, true);

    }

 

    public static<T> T toObject(Reader reader, Class<T> clazz)

            throwsJsonParseException, JsonMappingException, IOException {

        return toObject(reader, clazz, true);

    }

 

    public static<T> T toObject(URL url, Class<T> clazz) throwsJsonParseException, JsonMappingException, IOException {

        return toObject(url, clazz, true);

    }

 

    public static StringtoJsonString(Object obj, boolean serializeNull)

            throwsJsonGenerationException, JsonMappingException, IOException {

        return getMapper(serializeNull).writeValueAsString(obj);  //Yue

    }

 

    public static StringtoJsonAsString(Object obj, boolean serializeNull)

            throwsJsonGenerationException, JsonMappingException, IOException {

        return getMapper(serializeNull).writeValueAsString(obj);  //Yue

    }

 

    public static byte[]toJsonAsBytes(Object obj, boolean serializeNull)

            throwsJsonGenerationException, JsonMappingException, IOException {

        return getMapper(serializeNull).writeValueAsBytes(obj);  //Yue

    }

 

    public static voidtoJsonToFile(File file, Object obj, boolean serializeNull)

            throwsJsonGenerationException, JsonMappingException, IOException {

        getMapper(serializeNull).writeValue(file, obj);  //Yue

    }

 

    public static voidtoJsonToOutputStream(OutputStream out, Object obj, boolean serializeNull)

            throwsJsonGenerationException, JsonMappingException, IOException {

        getMapper(serializeNull).writeValue(out, obj);  //Yue

    }

 

    public static voidtoJsonToWriter(Writer writer, Object obj, boolean serializeNull)

            throwsJsonGenerationException, JsonMappingException, IOException {

        getMapper(serializeNull).writeValue(writer, obj);  //Yue

    }

 

    //泛型方法的使用,为什么要使用泛型方法呢?因为泛型类要在实例化的时候就指明类型,如果想换一种类型,不得不重新new一次,可能不够灵活;而泛型方法可以在调用的时候指明类型,更加灵活。

//  需要注意,一个static方法,无法访问泛型类的类型参数,所以,若要static方法需要使用泛型能力,必须使其成为泛型方法。

    public static<T> T toObject(String json, Class<T> clazz, boolean serializeNull

            throwsJsonParseException, JsonMappingException, IOException {

        return getMapper(serializeNull).readValue(json, clazz);

    }

 

    public static <T>T toObject(byte[] src, Class<T> clazz, boolean serializeNull)

            throwsJsonParseException, JsonMappingException, IOException {

        return getMapper(serializeNull).readValue(src, clazz);

    }

 

    public static<T> T toObject(File file, Class<T> clazz, boolean serializeNull)

            throwsJsonParseException, JsonMappingException, IOException {

        return getMapper(serializeNull).readValue(file, clazz);

    }

 

    public static<T> T toObject(InputStream input, Class<T> clazz, boolean serializeNull)

            throwsJsonParseException, JsonMappingException, IOException {

        return getMapper(serializeNull).readValue(input, clazz);

    }

 

    public static<T> T toObject(Reader reader, Class<T> clazz, boolean serializeNull)

            throwsJsonParseException, JsonMappingException, IOException {

        return getMapper(serializeNull).readValue(reader, clazz);

    }

 

    public static<T> T toObject(URL url, Class<T> clazz, boolean serializeNull)

            throwsJsonParseException, JsonMappingException, IOException {

        return getMapper(serializeNull).readValue(url, clazz);

    }

 

    public static voidsetDateFormat(DateFormat dateFormat) {

        getMapper(true).setDateFormat(dateFormat);

        getMapper(false).setDateFormat(dateFormat);

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值