fasterxml.jackson 教程1

最近项目使用的spring mvc框架,由于前端的采用了ui框架,所以对json 的操作就比较多,在这里我就把项目中用到的jackson教程给大家说说吧,因为看到网上的教程都挺模模糊糊的,感觉不是很清楚,对于一些挺有用的属性也没有很好的进行讲解,因为很多时候需要对一些不必要的属性进行过滤,当使用hibernate进行双向关联的时候,对于序列化成json的类就需要进行很好的过滤,否则会造成无限迭代

/**
 * Created with IntelliJ IDEA.
 * User: K
 * Date: 13-11-7
 * Time: 下午8:28
 * To change this template use File | Settings | File Templates.
 */
public class JacksonUtils {
    private  ObjectMapper mapper;
    private JacksonUtils(){
        mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);    //采用默认的模式  后面会有讲解
    };
    private JacksonUtils(JsonInclude.Include include)
    {
        mapper = new ObjectMapper();
        mapper.setSerializationInclusion(include);   //设置输出时包含属性的风格
    }

    public JacksonUtils(JsonInclude.Include include, SimpleDateFormat fmt) {
        mapper = new ObjectMapper();
        mapper.setSerializationInclusion(include);  //设置输出时包含属性的风格
        mapper.setDateFormat(fmt);

    }

    public <T> T fromJson(String jsonString, Class<T> clazz) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
         T t = null;
        try {
            t = mapper.readValue(jsonString, clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }
    public String toJson(Object object) throws MyException
    {
        String  json_str = "[]";
        try {
            json_str = mapper.writeValueAsString(object);
        } catch (Exception e) {
            json_str = "[]";
            throw new MyException(e);
        }finally {
            return json_str;
        }
    }
    //不需要记性属性的忽略
    public String toJson(Object object,String filterName) throws MyException {
        String  json_str = "[]";
        try {

            FilterProvider filterProvider = new SimpleFilterProvider().addFilter(filterName, SimpleBeanPropertyFilter.serializeAllExcept());
            json_str = mapper.writer(filterProvider).writeValueAsString(object);

        } catch (Exception e) {
            json_str = "[]";
            throw new MyException(e);
        }finally {
             return json_str;
        }
    }
    /*
    *
    * @param object 需要进行json序列化的类  可以是任何复杂的类
    * @param args 需要进行过滤的属性名称 类对象名称或者一些属性名称都可以进行过滤
    * */
    public String toJson(Object object,String []args,String filterName) throws MyException {
        String json = "[]";
        try
        {
            if (mapper==null)
            {

            }else
            {
                FilterProvider filterProvider = new SimpleFilterProvider().addFilter(filterName, SimpleBeanPropertyFilter.serializeAllExcept(args));
                json = mapper.writer(filterProvider).writeValueAsString(object);
            }
        }catch (Exception e)
        {
            json = "[]";
            throw new MyException(e);
        }finally {
            return json;
        }
    }
    public static JacksonUtils getInstance()
    {
        return new JacksonUtils();
    }
    /*
    * @param include
    *
    *   Include.Include.ALWAYS 默认
        Include.NON_DEFAULT 属性为默认值不序列化
        Include.NON_EMPTY 属性为 空(“”)  或者为 NULL 都不序列化
        Include.NON_NULL 属性为NULL 不序列化
    *这是一些有关include属性的选项,大家可以自己去尝试 我这里就不做过多的讲解了
    * */
    public static JacksonUtils getInstance(JsonInclude.Include include)
    {
        return new JacksonUtils(include);

    }
    //可以对时间的格式进行修改
    public static JacksonUtils getInstance(JsonInclude.Include include,SimpleDateFormat fmt)
    {
        //设置日期格式当使用jackson在处理时间时,默认是将时间输出为timestamps格式
        if (fmt==null)
            fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return new JacksonUtils(include,fmt);
    }
    public static void main(String args[])
    {
        JacksonUtils jacksonUtils = JacksonUtils.getInstance();
        JacksonUtils jacksonUtils1 = JacksonUtils.getInstance();
        UserMessage userMessage = new UserMessage();
        userMessage.setUser_account("123");
        userMessage.setEmail("@13123");
        try {
            Map<String,List> map = new HashMap<String,List>();
            Map<String,String>maps = new HashMap<String,String>();

            maps.put("message","arg");
            List list= new ArrayList();
            list.add(userMessage);
            map.put("String",list);

           String arg = jacksonUtils1.toJson(map,"UserMessage");
            String argv[] = {"user_account"};
            String str = jacksonUtils.toJson(userMessage,argv,"UserMessage");

            String json = jacksonUtils1.toJson(maps);
            System.out.println(arg);
            System.out.println(str);
            System.out.println(json);
        } catch (MyException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
}
/*
*
* 当需要对一个类的属性进行过滤的时候需要加上这个注解
* */
@JsonFilter("UserMessage")
class UserMessage  implements Serializable
{
    private String user_account;
    private String  email;

    public String getUser_account() {
        return user_account;
    }

    public void setUser_account(String user_account) {
        this.user_account = user_account;
    }

    public String getEmail() {
        return email;
    }

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

整个项目采用maven对jar包进行依赖管理所以附上maven的需要的jar

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.2.3</version>
        </dependency>


我就不做过多的讲解了 代码上的注释都挺详细的,需要注意的就是那个注解,必须加上否则会报错,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值