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 studentList = new ArrayList(); 

        studentList.add(student1); 

        studentList.add(student2); 

        studentList.add(student3); 

       Map studentMap = new HashMap(); 

        studentMap.put("1", student1); 

        studentMap.put("2", student2); 

        studentMap.put("3", student3); 

        Student json2object = null

       List json2list = null

       Map 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 --> JSON */ 

        String listforjson = mapper.writeValueAsString(studentList); 

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

        System.out.println(listforjson); 

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

         

        /* Map ----> JSON */ 

        String map4json = mapper.writeValueAsString(studentMap); 

        System.out.println("Map ----> 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 */ 

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

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

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

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

        /* JSON --> Map */ 

        json2map = mapper.readValue(map4json, newTypeReference>() {}); 

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

        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----> 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 ----> 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

 [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

 {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   readValue(byte[]src, Class valueType)

T   readValue(byte[]src, JavaType valueType)

T   readValue(byte[]src, TypeReference valueTypeRef)

T   readValue(Filesrc, Class valueType)

T   readValue(Filesrc, JavaType valueType)

T   readValue(Filesrc, TypeReference valueTypeRef)

T   readValue(InputStreamsrc, Class valueType)

T   readValue(InputStreamsrc, JavaType valueType)

T   readValue(InputStreamsrc, TypeReference valueTypeRef)

T   readValue(JsonNoderoot, Class valueType)

T   readValue(JsonNoderoot, JavaType valueType)

T   readValue(JsonNoderoot, TypeReference valueTypeRef)

T   readValue(JsonParserjp, Class valueType)

T   readValue(Readersrc, Class valueType)

T   readValue(Readersrc, JavaType valueType)

T   readValue(Readersrc, TypeReference valueTypeRef)

T   readValue(Stringcontent, Class valueType)

T   readValue(Stringcontent, JavaType valueType)

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 INCLUDE_NULL_MAPPER = new ThreadLocal();

 

    private static finalThreadLocal 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 toObject(String json, Class clazz)

            throwsJsonParseException, JsonMappingException, IOException {

        return toObject(json, clazz, true);

    }

 

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

            throwsJsonParseException, JsonMappingException, IOException {

        return toObject(src, clazz, true);

    }

 

    public static  T toObject(File file,Class clazz)

            throwsJsonParseException, JsonMappingException, IOException {

        return toObject(file, clazz, true);

    }

 

    public static T toObject(InputStream input, Class clazz)

            throwsJsonParseException, JsonMappingException, IOException {

        return toObject(input, clazz, true);

    }

 

    public static T toObject(Reader reader, Class clazz)

            throwsJsonParseException, JsonMappingException, IOException {

        return toObject(reader, clazz, true);

    }

 

    public static T toObject(URL url, Class 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 toObject(String json, Class clazz, boolean serializeNull

            throwsJsonParseException, JsonMappingException, IOException {

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

    }

 

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

            throwsJsonParseException, JsonMappingException, IOException {

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

    }

 

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

            throwsJsonParseException, JsonMappingException, IOException {

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

    }

 

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

            throwsJsonParseException, JsonMappingException, IOException {

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

    }

 

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

            throwsJsonParseException, JsonMappingException, IOException {

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

    }

 

    public static T toObject(URL url, Class 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);

    }

}

你可能感兴趣的:(Java,java,json)