JSON 之 jackson 用法

来源:互联网 发布:java windows相对路径 编辑:程序博客网 时间:2024/05/18 13:06


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); 上一条也可以如此设置;

       

        returnmapper

    } 

    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 StringfirstName

    private StringlastName

    publicName(){} 

    publicName(StringfirstName, String lastName) { 

        this.firstName =firstName

        this.lastName =lastName

    } 

    public StringgetFirstName() { 

        returnfirstName

    } 

    public voidsetFirstName(String firstName) { 

        this.firstName =firstName

    } 

    public StringgetLastName() { 

        returnlastName

    } 

    public voidsetLastName(String lastName) { 

        this.lastName =lastName

    } 

    public StringtoString() { 

        returnfirstName + " " +lastName

    } 

 

 

 class Student{ 

    private int id

    private Namename

    private StringclassName

    private DatebirthDay

    publicStudent(){} 

    publicStudent(intid, Name name, StringclassName, Date birthDay) { 

        super(); 

        this.id =id

        this.name =name

        this.className =className

        this.birthDay =birthDay

    } 

    public int getId(){ 

        returnid

    } 

    public void setId(intid) { 

        this.id =id

    } 

    public NamegetName() { 

        returnname

    } 

    public voidsetName(Name name) { 

        this.name =name

    } 

    public DategetBirthDay() { 

        returnbirthDay

    } 

    public voidsetBirthDay(Date birthDay) { 

        this.birthDay =birthDay

    } 

    public StringgetClassName() { 

        returnclassName

    } 

    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=WedAug 24 20:20:15 CST 2016, id=2, name=li si,classname=二班],Student [birthDay=WedAug 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=WedAug 24 20:20:15 CST 2016, id=2, name=li si,classname=二班],1=Student [birthDay=WedAug 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, SerializationConfigconfig)

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(booleanserializeNull) {

        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 {

        returntoJsonString(obj, true);

    }

 

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

        returntoJsonAsString(obj, true);

    }

 

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

        returntoJsonAsBytes(obj, true);

    }

 

    public static voidtoJsonToFile(File file, Object obj)

            throwsJsonGenerationException, JsonMappingException, IOException {

        toJsonToFile(file,obj, true);

    }

 

    public static voidtoJsonToOutputStream(OutputStreamout, Object obj)

            throwsJsonGenerationException, JsonMappingException, IOException {

        toJsonToOutputStream(out,obj, true);

    }

 

    public static voidtoJsonToWriter(Writerwriter, Object obj)

            throwsJsonGenerationException, JsonMappingException, IOException {

        toJsonToWriter(writer,obj, true);

    }

 

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

            throwsJsonParseException, JsonMappingException, IOException {

        returntoObject(json, clazz, true);

    }

 

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

            throwsJsonParseException, JsonMappingException, IOException {

        returntoObject(src, clazz, true);

    }

 

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

            throwsJsonParseException, JsonMappingException, IOException {

        returntoObject(file, clazz, true);

    }

 

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

            throwsJsonParseException, JsonMappingException, IOException {

        returntoObject(input, clazz, true);

    }

 

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

            throwsJsonParseException, JsonMappingException, IOException {

        returntoObject(reader, clazz, true);

    }

 

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

        returntoObject(url, clazz, true);

    }

 

    public static StringtoJsonString(Object obj,boolean serializeNull)

            throwsJsonGenerationException, JsonMappingException, IOException {

        returngetMapper(serializeNull).writeValueAsString(obj); //Yue

    }

 

    public static StringtoJsonAsString(Object obj,boolean serializeNull)

            throwsJsonGenerationException, JsonMappingException, IOException {

        returngetMapper(serializeNull).writeValueAsString(obj); //Yue

    }

 

    public static byte[]toJsonAsBytes(Objectobj, booleanserializeNull)

            throwsJsonGenerationException, JsonMappingException, IOException {

        returngetMapper(serializeNull).writeValueAsBytes(obj); //Yue

    }

 

    public static voidtoJsonToFile(File file, Object obj, booleanserializeNull)

            throwsJsonGenerationException, JsonMappingException, IOException {

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

    }

 

    public static voidtoJsonToOutputStream(OutputStreamout, Object obj,boolean serializeNull)

            throwsJsonGenerationException, JsonMappingException, IOException {

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

    }

 

    public static voidtoJsonToWriter(Writerwriter, 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, booleanserializeNull

            throwsJsonParseException, JsonMappingException, IOException {

        returngetMapper(serializeNull).readValue(json,clazz);

    }

 

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

            throwsJsonParseException, JsonMappingException, IOException {

        returngetMapper(serializeNull).readValue(src,clazz);

    }

 

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

            throwsJsonParseException, JsonMappingException, IOException {

        returngetMapper(serializeNull).readValue(file,clazz);

    }

 

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

            throwsJsonParseException, JsonMappingException, IOException {

        returngetMapper(serializeNull).readValue(input,clazz);

    }

 

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

            throwsJsonParseException, JsonMappingException, IOException {

        returngetMapper(serializeNull).readValue(reader,clazz);

    }

 

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

            throwsJsonParseException, JsonMappingException, IOException {

        returngetMapper(serializeNull).readValue(url,clazz);

    }

 

    public static voidsetDateFormat(DateFormatdateFormat) {

        getMapper(true).setDateFormat(dateFormat);

        getMapper(false).setDateFormat(dateFormat);

    }

}

0 0