博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java反射方法解析JSON
阅读量:5140 次
发布时间:2019-06-13

本文共 13821 字,大约阅读时间需要 46 分钟。

最近在做调用rest api的集成客户端,将api返回的JSON对象Mapping到指定的Model。用了个Mapping及java反射调用方法。对java反射和rest做了些了解。

api返回JSON数据:

定义mapping时取JSON数据的类型或者叫方式

下面这个表是JSON数据的字段和Model字段Mapping转换,其中field_type为8是需要调用方法处理后才能得到Model中相要的数据。

主要的解析都在下的DSIMPL类中

1 package com.ebao.eclaim.policy.mapping.ds;  2   3 import java.lang.reflect.Method;  4 import java.util.ArrayList;  5 import java.util.List;  6   7 import net.sf.json.JSONArray;  8 import net.sf.json.JSONObject;  9  10 import com.ebao.eclaim.common.bo.TClmPolicyMapping; 11 import com.ebao.eclaim.common.util.ClaimCst; 12 import com.ebao.eclaim.common.util.InsuredCst; 13 import com.ebao.eclaim.integration.policy.mapping.PolicyMappingCst; 14 import com.ebao.eclaim.integration.policy.mapping.PolicyMappingUtils; 15 import com.ebao.eclaim.policy.mapping.dao.TClmPolicyMappingDao; 16 import com.ebao.gs.pol.endo.ds.ws.copypolicy.GCAgentSOABO; 17 import com.ebao.gs.pol.endo.ds.ws.copypolicy.GCInsuredPersonSOABO; 18 import com.ebao.gs.pol.endo.ds.ws.copypolicy.GCInsuredPlanSOABO; 19 import com.ebao.gs.pol.endo.ds.ws.copypolicy.GCPolicyCoverSOAModel; 20 import com.ebao.gs.pol.endo.ds.ws.copypolicy.GCPolicyCtSOABO; 21 import com.ebao.gs.pol.endo.ds.ws.copypolicy.GCPolicyCtSOAModel; 22 import com.ebao.gs.pol.endo.ds.ws.copypolicy.GCPolicyHolderSOABO; 23 import com.ebao.gs.pol.endo.ds.ws.copypolicy.GCSInsuredSOABO; 24 import com.ebao.gs.pol.endo.ds.ws.copypolicy.GCSPolicySOABO; 25 import com.ebao.gs.pol.endo.ds.ws.copypolicy.GCSVehicleInsuredSOABO; 26 import com.ebao.gs.pol.endo.ds.ws.copypolicy.GSDriverSOABO; 27  28 /** 29  * 2015-10-14 30  * @author fengying.ye 31  * 32  */ 33 public class PolicyMappingDSImpl implements PolicyMappingDS { 34     TClmPolicyMappingDao mappingDao; 35     public void forTest(){ 36          37     } 38     public GCSPolicySOABO mappingPolicy() throws Exception{ 39         JSONObject policy =JSONObject.fromObject("{PolicyNo:20000011}"); 40         GCSPolicySOABO gcsPolicySoabo = new GCSPolicySOABO(); 41         List
policyFields = mappingDao.getFieldList(PolicyMappingCst.MODEL_POLICY, null); 42 for(TClmPolicyMapping field : policyFields){ 43 Object value = this.getFieldValue(policy, field); 44 if(value != null){ 45 this.setPropertyValue(gcsPolicySoabo, field.getClaimField(), value); 46 } 47 } 48 49 handleAgent(gcsPolicySoabo,policy.getLong(PolicyMappingCst.NODE_AGENT_ID)); 50 handleCustomerList(gcsPolicySoabo,policy.getJSONArray(PolicyMappingCst.NODE_POLICY_CUSTOMER_LIST)); 51 handlePolicyLobList(gcsPolicySoabo,policy.getJSONArray(PolicyMappingCst.NODE_POLICY_LOB_LIST)); 52 53 return gcsPolicySoabo; 54 } 55 private void handlePolicyLobList(GCSPolicySOABO gcsPolicySoabo,JSONArray policyLobList) throws Exception{ 56 for(int i=0;i
insuredList = new ArrayList
(); 61 JSONArray riskList = policyLob.getJSONArray(PolicyMappingCst.NODE_POLICY_RISK_LIST); 62 for(int j=0;j
insuredList,JSONObject risk,JSONArray driverList,long productId) throws Exception{ 73 GCSInsuredSOABO insured = new GCSInsuredSOABO(); 74 List
insuredFields = mappingDao.getFieldList(PolicyMappingCst.MODEL_INSURED, productId); 75 for(TClmPolicyMapping field : insuredFields){ 76 Object value = this.getFieldValue(risk, field); 77 if(value != null){ 78 this.setPropertyValue(insured, field.getClaimField(), value); 79 } 80 } 81 insured.setInsuredCategory(InsuredCst.VEHICLE_INSURED); 82 handlePlanList(insured,risk); 83 handleVehicle(insured,risk,driverList); 84 handleCoverage(insured,risk.getJSONArray(PolicyMappingCst.NODE_POLICY_COVERAGE_LIST)); 85 } 86 87 private void handleCoverage(GCSInsuredSOABO insured,JSONArray ctList) throws Exception{ 88 List
ctModels = new ArrayList
(); 89 List
ctFields = mappingDao.getFieldList(PolicyMappingCst.MODEL_CT, null); 90 for(int i=0;i
());107 ctModels.add(ctModel);108 }109 insured.setGcPolicyCtModelList(ctModels);110 }111 private void handleVehicle(GCSInsuredSOABO insured,JSONObject risk,JSONArray driverList) throws Exception{112 GCSVehicleInsuredSOABO vehicle = new GCSVehicleInsuredSOABO();113 List
insuredFields = mappingDao.getFieldList(PolicyMappingCst.MODEL_VEHICLE, null);114 for(TClmPolicyMapping field : insuredFields){115 Object value = this.getFieldValue(risk, field);116 if(value != null){117 this.setPropertyValue(vehicle, field.getClaimField(), value);118 }119 }120 handleDriverList(vehicle,driverList);121 insured.setGcsvehicleInsuredSOABO(vehicle);122 }123 private void handleDriverList(GCSVehicleInsuredSOABO vehicle , JSONArray driverList) throws Exception{124 List
dirverList = new ArrayList
();125 List
insuredFields = mappingDao.getFieldList(PolicyMappingCst.MODEL_DRIVER, null);126 for(int i=0;i
planList = new ArrayList
();141 GCInsuredPlanSOABO plan = new GCInsuredPlanSOABO();142 plan.setPlanCode(risk.getString(PolicyMappingCst.NODE_PLAN_CODE));143 insured.setInsuredPlanList(planList);144 }145 146 private void handleCustomerList(GCSPolicySOABO gcsPolicySoabo,JSONArray customerList) throws Exception{147 List
insuredList = new ArrayList
(); 148 GCPolicyHolderSOABO policyHolder = new GCPolicyHolderSOABO();149 List
customerFields = mappingDao.getFieldList(PolicyMappingCst.MODEL_CUSTOMER, null);150 for(int i=0;i
insuredList, JSONObject insuredPerson, List
customerFields) throws Exception{162 GCInsuredPersonSOABO insured = new GCInsuredPersonSOABO();163 for(TClmPolicyMapping field : customerFields){164 Object value = this.getFieldValue(insuredPerson, field);165 if(value != null){166 this.setPropertyValue(insured, field.getClaimField(), value);167 }168 }169 insuredList.add(insured);170 }171 private void handlePolicyHolder(GCPolicyHolderSOABO policyHolder, JSONObject holder, List
customerFields) throws Exception{172 for(TClmPolicyMapping field : customerFields){173 Object value = this.getFieldValue(holder, field);174 if(value != null){175 this.setPropertyValue(policyHolder, field.getClaimField(), value);176 }177 }178 }179 180 private void handleAgent(GCSPolicySOABO gcsPolicySoabo, Long agentId){181 GCAgentSOABO agent = new GCAgentSOABO();182 //invoke SC api183 184 gcsPolicySoabo.setAgent(agent);185 }186 187 private Object getFieldValue(JSONObject jsonObj,TClmPolicyMapping mapping) throws Exception{188 String fieldType = mapping.getFieldType();189 String policyField = mapping.getPolicyField();190 if(PolicyMappingCst.FIELD_TYPE_STRING.equals(fieldType)){191 return jsonObj.getString(policyField);192 }else if(PolicyMappingCst.FIELD_TYPE_LONG.equals(fieldType)){193 return jsonObj.getLong(policyField);194 }else if(PolicyMappingCst.FIELD_TYPE_DOUBLE.equals(fieldType)){195 return jsonObj.getDouble(policyField);196 }else if(PolicyMappingCst.FIELD_TYPE_INT.equals(fieldType)){197 return jsonObj.getInt(policyField);198 }else if(PolicyMappingCst.FIELD_TYPE_BOOLEAN.equals(fieldType)){199 return jsonObj.getBoolean(policyField);200 }else if(PolicyMappingCst.FIELD_TYPE_METHOD.equals(fieldType)){201 return this.invokeUtilsMethod(mapping.getMethodName(), jsonObj.getString(policyField));202 }203 return null;204 }205 public void setPropertyValue(Object instance, String fieldName, Object fieldValue) throws Exception{206 Class instanceClass = instance.getClass();207 Method method = instanceClass.getDeclaredMethod("set"+fieldName, fieldValue.getClass());208 method.invoke(instance, fieldValue);209 }210 public Object invokeUtilsMethod(String methodName, Object... paras)211 throws Exception {212 Class[] classArray = new Class[paras.length];213 for(int i=0;i
1 package com.ebao.eclaim.integration.policy.mapping; 2 /** 3  * 2015-10-14 4  * @author fengying.ye 5  * 6  */ 7 public class PolicyMappingCst { 8     //T_CLM_POLICY_MAPPING_FIELD_TYPE 9     public static final String FIELD_TYPE_INT = "1";10     public static final String FIELD_TYPE_DOUBLE = "2";11     public static final String FIELD_TYPE_LONG = "3";12     public static final String FIELD_TYPE_STRING = "4";13     public static final String FIELD_TYPE_BOOLEAN = "5";14     public static final String FIELD_TYPE_ARRAY = "6";15     public static final String FIELD_TYPE_OBJECT = "7";16     public static final String FIELD_TYPE_METHOD = "8";17     18     public static final String MODEL_POLICY = "GCSPolicySOABO";19     public static final String MODEL_CUSTOMER = "GCPolicyHolderSOABO";20     public static final String MODEL_INSURED = "GCPolicyHolderSOABO";21     public static final String MODEL_VEHICLE = "GCSVehicleInsuredSOABO";22     public static final String MODEL_DRIVER = "GSDriverSOABO";23     public static final String MODEL_CT = "GCPolicyCtSOABO";24     25     public static final String NODE_AGENT_ID = "AgentId";26     public static final String NODE_POLICY_CUSTOMER_LIST = "PolicyCustomerList";27     public static final String NODE_IS_INSURED = "IsInsured";28     public static final String NODE_IS_POLICYHOLDER = "IsPolicyHolder";29     public static final String NODE_CUSTOMER = "Customer";30     31     public static final String NODE_POLICY_LOB_LIST = "PolicyLobList";32     public static final String NODE_PRODUCT_ID = "ProductId";33     public static final String NODE_DRIVER_LIST = "DriverList";34     public static final String NODE_POLICY_RISK_LIST = "PolicyRiskList";35     public static final String NODE_RISK_TYPE = "@type";36     public static final String RISK_TYPE_VEHICLE = "PolicyRisk-Vehicle";37     public static final String NODE_PLAN_CODE = "PlanCode";38     public static final String NODE_POLICY_COVERAGE_LIST = "PolicyCoverageList";39 }
1 package com.ebao.eclaim.integration.policy.mapping; 2  3 import java.math.BigDecimal; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6  7 import com.ebao.gs.pub.util.StringUtils; 8  9 public class PolicyMappingUtils {10     11     public Date formateDate(String dataStr) throws Exception{12         if(StringUtils.isNullOrEmpty(dataStr)) return null;13         SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");14         return sdf.parse(dataStr.replace("T", " "));15     }16     17     public BigDecimal stringToBigdecimal(String dataStr) throws Exception{18         if(StringUtils.isNullOrEmpty(dataStr)) return null;19         return new BigDecimal(dataStr);20     }21     public String getInsuredExtContent(String content){22         return "insuredId="+content+";";23     }24 }

 Junit测试例子

1 package com.ebao.eclaim.policy.mapping.ds; 2  3 import static org.junit.Assert.*; 4  5 import java.util.List; 6  7 import org.junit.Before; 8 import org.junit.Test; 9 10 import com.ebao.eclaim.common.bo.TClmPolicyMapping;11 import com.ebao.eclaim.integration.policy.mapping.PolicyMappingCst;12 import com.ebao.eclaim.policy.mapping.dao.hibernate.TClmPolicyMappingDaoHibernate;13 14 public class PolicyMappingDSImplTest {15 16     @Before17     public void setUp() throws Exception {18     }19 20     @Test21     public void testForTest() {22         TClmPolicyMappingDaoHibernate dh = new TClmPolicyMappingDaoHibernate();23         List
mappingList = dh.getFieldList(PolicyMappingCst.MODEL_POLICY, null);24 System.out.println("===========; "+mappingList.size());25 assertEquals(true, mappingList.size() > 1);26 27 28 29 // PolicyMappingDSImpl ds = new PolicyMappingDSImpl();30 // JSONObject policy =JSONObject.fromObject("{FinalPremium:998}");31 // try {32 // BigDecimal data = (BigDecimal)ds.invokeUtilsMethod("stringToBigdecimal", policy.getString("FinalPremium"));33 // System.out.println("==============================: "+data);34 // assertEquals(new BigDecimal("998"), data);35 // } catch (Exception e) {36 // e.printStackTrace();37 // }38 39 // PolicyMappingDSImpl ds = new PolicyMappingDSImpl();40 // SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");41 // try {42 // Date date = (Date)ds.invokeUtilsMethod("formateDate", "2011-01-13T00:00:00");43 // System.out.println("==============================: "+date);44 // assertEquals(sdf.parse("2011-01-13 00:00:00"), date);45 // } catch (Exception e) {46 // e.printStackTrace();47 // }48 49 // PolicyMappingDSImpl ds = new PolicyMappingDSImpl();50 // SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");51 // JSONObject policy =JSONObject.fromObject("{EffectDate:\"2011-01-13T00:00:00\"}");52 // GCSPolicySOABO gcsPolicySoabo = new GCSPolicySOABO();53 // try {54 // System.out.println("+++++++++++++++===----------: "+policy.getString("EffectDate").replace("T", " "));55 // ds.setPropertyValue(gcsPolicySoabo, "EffectDate", sdf.parse(policy.getString("EffectDate").replace("T", " ")));56 // assertEquals(sdf.parse("2011-01-13 00:00:00"), gcsPolicySoabo.getEffectDate());57 // } catch (Exception e) {58 // e.printStackTrace();59 // }60 61 62 // JSONObject policy =JSONObject.fromObject("{PolicyNo:20000011}");63 // GCSPolicySOABO gcsPolicySoabo = new GCSPolicySOABO();64 // PolicyMappingDSImpl ds = new PolicyMappingDSImpl();65 // try {66 // ds.setPropertyValue(gcsPolicySoabo, "PolicyNo", policy.getString("PolicyNo"));67 // assertEquals("20000011", gcsPolicySoabo.getPolicyNo());68 // } catch (Exception e) {69 // e.printStackTrace();70 // }71 }72 73 }

 

转载于:https://www.cnblogs.com/yefy/p/4885256.html

你可能感兴趣的文章
洛谷P3676 小清新数据结构题(动态点分治)
查看>>
九校联考-DL24凉心模拟Day2T1 锻造(forging)
查看>>
Cortex M3/M4 学习摘要(二)
查看>>
C#时间的味道——任时光匆匆我只在乎你
查看>>
(1)数据结构——线性表(数组)实现
查看>>
SpringMyBatis解析2-SqlSessionFactoryBean
查看>>
按照excel文档中的内容在当前cad图纸中自动排布实体
查看>>
Winform开发框架之图表报表在线设计器2-图表-SNF.EasyQuery项目--SNF快速开发平台3.3-Spring.Net.Framework...
查看>>
C#基础第八天-作业-设计类-面向对象方式实现两个帐户之间转账
查看>>
洛谷 P3237 [HNOI2014]米特运输
查看>>
Attributes.Add用途与用法
查看>>
JavaScript面向对象初探——封装和继承
查看>>
L2-001 紧急救援 (dijkstra+dfs回溯路径)
查看>>
【概率】poj 2096:Collecting Bugs
查看>>
javascript 无限分类
查看>>
【自制插件】MMD4Maya
查看>>
解决linux服务器乱码
查看>>
mapbox.gl文字标注算法基本介绍
查看>>
【C++】异常简述(二):C++的异常处理机制
查看>>
web.config在哪里
查看>>