Jackson学习实例

阅读更多

一.Jackson使用Tree Model读取以及更新JSON

        使用ObjectMapper,可以以类似读取DOM的方式读取JSON,实例如下:

package com.bijian.study;

import java.util.Iterator;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;

public class JacksonDemo01 {

    public static void main(String[] args) {
        JacksonParseJSON();
        JacksonUpdateJSON();
    }
    
    private static void JacksonParseJSON() {
        
        System.out.println("JacksonParseJSON():");
        System.out.println("***************************************");
        String str = "{\"weatherinfo\":{\"city\":\"杭州\",\"city_en\":\"hangzhou\",\"date_y\":\"2014年1月12日\",\"date\":\"2016-03-17 15:46:20\",\"week\":\"星期日\",\"fchh\":\"11\",\"cityid\":\"101210101\"}}";
        ObjectMapper m = new ObjectMapper();  
        try {
            JsonNode rootNode = m.readTree(str);
            
            JsonNode weaNode = rootNode.get("weatherinfo");  
            System.out.println(weaNode);  
            System.out.println(weaNode.get("city"));  
              
            // Use Iterator to traverse to tree  
            Iterator keys = weaNode.getFieldNames();   
            while(keys.hasNext()){  
                String fieldName = keys.next();  
                System.out.println(fieldName + ": " + weaNode.get(fieldName).getTextValue());  
            }
            System.out.println("***************************************");
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
    
    private static void JacksonUpdateJSON() {
        
        System.out.println("JacksonUpdateJSON():");
        System.out.println("***************************************");
        ObjectMapper mapper = new ObjectMapper();
        // will be of type ObjectNode  
        JsonNode rootNode = mapper.createObjectNode();
        ((ObjectNode) rootNode).put("name", "jingshou");  
        ((ObjectNode) rootNode).put("id", 523);  
        ((ObjectNode) rootNode).put("age", 30);   
        System.out.println(rootNode);  
        
        try {
            String json = mapper.writeValueAsString(rootNode);
            System.out.println(json);  
            ((ObjectNode) rootNode).remove("id");  
            System.out.println(rootNode);
            System.out.println("***************************************");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

运行结果:

JacksonParseJSON():
***************************************
{"city":"杭州","city_en":"hangzhou","date_y":"2014年1月12日","date":"2016-03-17 15:46:20","week":"星期日","fchh":"11","cityid":"101210101"}
"杭州"
city: 杭州
city_en: hangzhou
date_y: 2014年1月12日
date: 2016-03-17 15:46:20
week: 星期日
fchh: 11
cityid: 101210101
***************************************
JacksonUpdateJSON():
***************************************
{"name":"jingshou","id":523,"age":30}
{"name":"jingshou","id":523,"age":30}
{"name":"jingshou","age":30}
***************************************

 

二.Jackson的对象与json之间的转换

package com.bijian.study;

import java.io.StringWriter;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

import com.bijian.study.dto.User;
import com.bijian.study.dto.Weather;

public class JacksonDemo02 {
    
    public static void main(String[] args) {
        JacksonChangeJSON01();
        JacksonChangeJSON02();
    }
    
    /**
     * Jackson的对象与json之间的转换
     */
    private static void JacksonChangeJSON01() {
        
        StringBuilder sb = new StringBuilder();  
        sb.append("{");  
        sb.append("\"name\" : { \"first\" : \"Joe\", \"last\" : \"Sixpack\" },");  
        sb.append("\"gender\" : \"MALE\",");  
        sb.append("\"verified\" : false,");  
        sb.append("\"userImage\" : \"Rm9vYmFyIQ==\"");  
        sb.append("}");  
          
        ObjectMapper mapper = new ObjectMapper();
        try {
            User user = mapper.readValue(sb.toString(), User.class);
            ObjectMapper mapper2 = new ObjectMapper();    
            StringWriter sw = new StringWriter();    
            JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);    
            mapper2.writeValue(gen, user);    
            gen.close();    
            String json = sw.toString();  
            System.out.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * Jackson的对象与json之间的转换
     */
    private static void JacksonChangeJSON02() {
        
        String str = "{\"city\":\"杭州\",\"city_en\":\"hangzhou\",\"date_y\":\"2014年1月12日\",\"date\":\"2016-03-17\",\"week\":\"星期日\",\"fchh\":\"11\",\"cityid\":\"101210101\"}";
        ObjectMapper m = new ObjectMapper();
        try {
            Weather w = m.readValue(str, Weather.class);
            ObjectMapper mapper2 = new ObjectMapper();    
            StringWriter sw = new StringWriter();    
            JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);    
            mapper2.writeValue(gen, w);    
            gen.close();    
            String json = sw.toString();  
            System.out.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package com.bijian.study.dto;

public class User {  
    
    public enum Gender {  
        MALE, FEMALE  
    };  
  
    public static class Name {  
        private String _first, _last;  
  
        public String getFirst() {  
            return _first;  
        }  
  
        public String getLast() {  
            return _last;  
        }  
  
        public void setFirst(String s) {  
            _first = s;  
        }  
  
        public void setLast(String s) {  
            _last = s;  
        }  
    }  
  
    private Gender _gender;  
    private Name _name;  
    private boolean _isVerified;  
    private byte[] _userImage;  
  
    public Name getName() {  
        return _name;  
    }  
  
    public boolean isVerified() {  
        return _isVerified;  
    }  
  
    public Gender getGender() {  
        return _gender;  
    }  
  
    public byte[] getUserImage() {  
        return _userImage;  
    }  
  
    public void setName(Name n) {  
        _name = n;  
    }  
  
    public void setVerified(boolean b) {  
        _isVerified = b;  
    }  
  
    public void setGender(Gender g) {  
        _gender = g;  
    }  
  
    public void setUserImage(byte[] b) {  
        _userImage = b;  
    }  
}
package com.bijian.study.dto;

import java.util.Date;

public class Weather {

    private String city;
    private String city_en;
    private String date_y;
    private Date date;
    private String week;
    private int fchh;
    private String cityid;
    
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getCity_en() {
        return city_en;
    }
    public void setCity_en(String city_en) {
        this.city_en = city_en;
    }
    public String getDate_y() {
        return date_y;
    }
    public void setDate_y(String date_y) {
        this.date_y = date_y;
    }
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
    public String getWeek() {
        return week;
    }
    public void setWeek(String week) {
        this.week = week;
    }
    public int getFchh() {
        return fchh;
    }
    public void setFchh(int fchh) {
        this.fchh = fchh;
    }
    public String getCityid() {
        return cityid;
    }
    public void setCityid(String cityid) {
        this.cityid = cityid;
    }
}

运行结果:

{"verified":false,"gender":"MALE","userImage":"Rm9vYmFyIQ==","name":{"first":"Joe","last":"Sixpack"}}
{"city":"杭州","city_en":"hangzhou","date_y":"2014年1月12日","date":1458172800000,"week":"星期日","fchh":11,"cityid":"101210101"}

 

三.设置时间格式

package com.bijian.study;

import java.io.StringWriter;
import java.text.SimpleDateFormat;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;

import com.bijian.study.dto.Weather;

public class JacksonDemo03 {

    /**
     * Json时间格式
     */
    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    
    static ObjectMapper mapper = null;
    
    static{
            mapper = new ObjectMapper();
            SimpleDateFormat fmt = new SimpleDateFormat(DATE_FORMAT);  
            mapper.setDateFormat(fmt);
            mapper.enable(Feature.WRITE_NULL_MAP_VALUES);
            mapper.enable(Feature.WRITE_EMPTY_JSON_ARRAYS);
    }

    public static  T parse(JsonNode root, Class rootType) {
        try {
            return mapper.readValue(root, rootType);
        } catch (Exception e) {
            throw new RuntimeException("JsonNode转换" + rootType.getName() + "异常", e);
        }
    }
    
    public static void main(String[] args) {
        jacksonChangeJson();
    }
    
    private static void jacksonChangeJson() {

        String str = "{\"weatherinfo\":{\"city\":\"杭州\",\"city_en\":\"hangzhou\",\"date_y\":\"2014年1月12日\",\"date\":\"2016-03-17 15:46:20\",\"week\":\"星期日\",\"fchh\":\"11\",\"cityid\":\"101210101\"}}";  
        try {
            JsonNode rootNode = mapper.readTree(str);
            
            JsonNode weaNode = rootNode.get("weatherinfo");
            Weather w = mapper.readValue(weaNode, Weather.class);
            
//            Weather w = parse(weaNode, Weather.class);
            
            ObjectMapper mapper2 = new ObjectMapper();    
            StringWriter sw = new StringWriter();    
            JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);    
            mapper2.writeValue(gen, w);    
            gen.close();    
            String json = sw.toString();  
            System.out.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

运行结果 :

{"city":"杭州","city_en":"hangzhou","date_y":"2014年1月12日","date":1458200780000,"week":"星期日","fchh":11,"cityid":"101210101"}

 

四.抽取完善实例

package com.bijian.study;

import java.io.StringWriter;
import java.text.SimpleDateFormat;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;

import com.bijian.study.dto.BaseInfoDTO;

public class JacksonDemo04 {

    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    
    static ObjectMapper mapper = null;
    
    static{
            mapper = new ObjectMapper();
            SimpleDateFormat fmt = new SimpleDateFormat(DATE_FORMAT);  
            mapper.setDateFormat(fmt);
            mapper.enable(Feature.WRITE_NULL_MAP_VALUES);
            mapper.enable(Feature.WRITE_EMPTY_JSON_ARRAYS);
    }

    public static  T parse(JsonNode root, Class rootType) {
        try {
            return mapper.readValue(root, rootType);
        } catch (Exception e) {
            throw new RuntimeException("JsonNode转换" + rootType.getName() + "异常", e);
        }
    }
    
    public static void main(String[] args) {
        jacksonChangeJson();
    }
    
    private static void jacksonChangeJson() {
        
        String str = "{\"id\":\"FC75C4AE61A04B49912C789A72D47F16\",\"detailList\":[{\"id\":\"D4416D08A9CE4AB882AA7EFC3EE66B14\",\"baseInfoId\":null,\"companyCode\":\"203\",\"companyName\":\"支付宝\",\"scale\":0.85},{\"id\":\"1392C28C4C6E422983F4EACC0C52A014\",\"baseInfoId\":null,\"companyCode\":\"211\",\"companyName\":\"微信\",\"scale\":0.15}],\"mark\":\"2\"}";
        try {
            //法一:ObjectMapper的readValue方法操作JsonNode节点,一般在解析JsonNode中的子节点时用到
//            JsonNode rootNode = mapper.readTree(str);
//            BaseInfoDTO c = mapper.readValue(rootNode, BaseInfoDTO.class);
            
            //法二:ObjectMapper的readValue方法做下封装
//            JsonNode rootNode = mapper.readTree(str);
//            BaseInfoDTO c = parse(rootNode, BaseInfoDTO.class);
            
            //法三:ObjectMapper的readValue方法直接操作JSON串
            BaseInfoDTO c = mapper.readValue(str, BaseInfoDTO.class);
            
            ObjectMapper mapper2 = new ObjectMapper();    
            StringWriter sw = new StringWriter();    
            JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);    
            mapper2.writeValue(gen, c);    
            gen.close();    
            String json = sw.toString();  
            System.out.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package com.bijian.study.dto;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

public class AbstractDTO {

    /**
     * 序列化
     */
    private static final long serialVersionUID = -6492889909372878745L;

    /**
     * 主键id
     */
    private String id;
    
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    
    /**
     * ToString方法
     */
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE);
    }
}
package com.bijian.study.dto;

import java.util.List;

public class BaseInfoDTO extends AbstractDTO {

    /**
     * 序列化
     */
    private static final long serialVersionUID = -1354767346065648328L;
    /**
     * 详细信息描述
     */
    private List detailList;

    private String mark;

    public List getDetailList() {
        return detailList;
    }

    public void setDetailList(List detailList) {
        this.detailList = detailList;
    }

    public String getMark() {
        return mark;
    }

    public void setMark(String mark) {
        this.mark = mark;
    }
}
package com.bijian.study.dto;

public class DetailDTO extends AbstractDTO {

    /**
     * 序列化
     */
    private static final long serialVersionUID = -8405894524309728426L;
    
    /**基本信息(外键)*/
    private String baseInfoId;
    private String companyCode;
    private String companyName;
    private Double scale;
    
    public String getBaseInfoId() {
        return baseInfoId;
    }
    public void setBaseInfoId(String baseInfoId) {
        this.baseInfoId = baseInfoId;
    }
    public String getCompanyCode() {
        return companyCode;
    }
    public void setCompanyCode(String companyCode) {
        this.companyCode = companyCode;
    }
    public String getCompanyName() {
        return companyName;
    }
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }
    public Double getScale() {
        return scale;
    }
    public void setScale(Double scale) {
        this.scale = scale;
    }
}

运行结果:

{"id":"FC75C4AE61A04B49912C789A72D47F16","detailList":[{"id":"D4416D08A9CE4AB882AA7EFC3EE66B14","baseInfoId":null,"companyCode":"203","companyName":"支付宝","scale":0.85},{"id":"1392C28C4C6E422983F4EACC0C52A014","baseInfoId":null,"companyCode":"211","companyName":"微信","scale":0.15}],"mark":"2"}

 

  • JacksonDemo.rar (1.2 MB)
  • 下载次数: 0

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