首页 > Web开发 > 详细

谷歌JSON技术--转换成JSON忽略某些属性

时间:2017-05-27 12:02:47      阅读:364      评论:0      收藏:0      [点我收藏+]

 

公司小项目刚开始。自己编写了一些Util方法

本公司用谷歌的json技术来处理json,通过接收HttpServletRequest 的输入流来转化成实体

pom.xml 如下

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>

方法如下:

public static <T> T ConvertJson(HttpServletRequest request,Type typeOfT,String[] ignoreFields) throws IOException,JsonSyntaxException{
  HttpServletRequest temp_request = request;
  String json = CommonUtil.getRequestString(temp_request); //通过request.getReader()方法来获取字符串方法,这里就不贴出来了
  if(json.equals("")){
    throw new NoJsonDataException();
  } 

  //需要忽略的字段集合
  List<String> list = new ArrayList<>();
  for(String str:ignoreFields){
    list.add(str);
  }

  //设置时间格式
  Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
    .setExclusionStrategies(new ExclusionStrategy(){

    //需要忽略的字段名

    @Override
    public boolean shouldSkipField(FieldAttributes f) {
      // TODO Auto-generated method stub
      return list.contains(f.getName());
    }

    //需要清空的字段类型

    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
    // TODO Auto-generated method stub
      return clazz.getName().equals(Date.class.getName());
    }
  }).create();


  return (T) gson.fromJson(json, typeOfT);
}

谷歌JSON技术--转换成JSON忽略某些属性

原文:http://www.cnblogs.com/hughli/p/6912097.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!