产品开发过程中的 JSON 转换问题

产品开发过程中的 JSON 转换问题

1. 实体 JSON 转换报错

报错关键词:
原因:Property ‘autoRefetch’ has no getter method in class ‘class oracle.jdbc.driver.OracleResultSetImpl’

代码:

PmbbDept dept = dao.get(PmbbDept.class, "8a8181bb64abc03c0164abea3d26002a");
Set<PmbbDept> childs = dept.getSubDepts();
PmbbCompany com = dept.getPmbbCompany();
当返回的对象存在关联对象引用时,

返回方式1
this.addParameter("entity", dept );
返回方式2
this.returnData.toParam(dept );

处理方式 1:将关联引用的对象置为 null,改动量大

PmbbDept dept = dao.get(PmbbDept.class, "8a8181bb64abc03c0164abea3d26002a");
dept.setPmbbCompany(null);
dept.setSubDepts(null);
this.returnData.toParam(dept );

image.png

处理方式 2:修改 JSONUtil.getDefaultJsonConfig,过滤掉 hibernate 生成的代理对象 (org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer@4fbafab6)

实体中的集合也可以转换出对应的结果

jsonConfig.setJsonPropertyFilter(new PropertyFilter(){
     @Override
      public boolean apply(Object arg0, String arg1, Object arg2)
      {
            if(arg0.getClass().toString().contains("javassist"))
                  return true;
            return false;
      }
   }
);

image.png

2. 接口返回数据的封装

产品中新增 JSONObjectTransformer 和 JSONArrayTransformer,方便直接转换返回结果,不用继续拼装

        JSONObject ret = new JSONObject();

        try
        {
            JSONObject data = new JSONObject();

            String hql1 = "select r.equipCode as equipCode,r.equipName as equipName,u.code as statusCode,u.name as statusName from MbfEquipment r,MbbUdi u where u.id=r.runStatus and r.equipCode = ? and r.isDelete=0 order by r.equipCode";
            JSONObject status = (JSONObject) bppDao.createQuery(hql1, equipCode).setResultTransformer(new JSONObjectTransformer()).uniqueResult();

            String hql2 = "select t.id, t.dispatchCode,t.plannedStartTime,t.plannedFinishTime,t.workOrderCode from UexpTrackOrder t where t.isDelete=0 and t.disCodeState!=3 and t.opCode=? order by t.dispatchCode desc";
            JSONArray tasks = (JSONArray) bppDao.createQuery(hql2, equipCode).setResultTransformer(new JSONArrayTransformer()).uniqueResult();

            data.put("status", status);
            data.put("tasks", tasks);

            ret.put("data", data);
            ret.put("errcode", 0);
            ret.put("errmsg", "");

        } catch (Exception e)
        {
            MestarLogger.error(e);
            ret.put("errcode", -1);
            ret.put("errmsg", "后台异常!" + e.getMessage());
        }
        return ret;

3. 指定 JSON 转换的命名配置

import org.codehaus.jackson.map.annotate.JsonSerialize;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;

//转换为JSON时忽略为NULL的属性
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
//指定整体的命名方式
@JsonNaming(PropertyNamingStrategy.PascalCaseStrategy.class)
public class ExtTaskVO implements Serializable
{
//指定JSON转换的名称
@JsonProperty(value = "EndDate")
private String endDate;