请通过浏览器功能收藏网页

java 利用反射 解析webservice 的JSON接口数据应用(依赖alibaba json包) 实用小功能

发布时间:2019-01-15 14:33:25  作者:本站编辑  来源:本站原创  浏览次数:
www.javainfo.com.cn 上干货 欢迎收藏


数据格式准备  这里需要与接口进行对应处理 


这里包资源JAR包放到这里:   fastjson-1.1.6.zip  请右键点击另存为下载jar包

Model 对象:

                public class ModelInfo{

                 /**

                 * 姓名

                 */

                 private String User_real_name;

                

                 /**

                 * 项目位置

                 */

                 private String Item_seat;

                

                 /**

                 * 合同签约日期

                 */

                 private String Contract_date;

                

                 /**

                 * 合同价格

                 */

                 private java.math.BigDecimal Contract_price;

                }


接口调用

      //http 协议请求 .net webservice json服务2

      public StringBuilder httpGetInfo(String uri) {

URL root;

StringBuilder stringb = new StringBuilder();

InputStream input = null;

URLConnection rootCon = null;

try {

root = new URL(uri);

rootCon = root.openConnection();

int len = rootCon.getContentLength();

String trimTool = new String("");

if (len > 0) {

System.out.println("=== content ===");

input = rootCon.getInputStream();

InputStreamReader isr = new InputStreamReader(input,

Charset.forName("UTF-8"));

char[] target = new char[50480];

while (isr.read(target) != -1) {

System.out.println(trimTool.valueOf(target).trim());

stringb.append(trimTool.valueOf(target).trim());

}

} else {

System.out.println("No Content Available!");

}

} catch (Exception e) {

e.printStackTrace();

} finally {

if(input != null ){

try {

input.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return stringb;

}

//http 协议请求 .net webservice json服务1

public String httpGetInfoForLouDong(String uri) {

URL root;

StringBuffer content = new StringBuffer();

InputStream input = null;

HttpURLConnection rootCon = null;

BufferedReader in = null;

try {

root = new URL(uri);

rootCon = (HttpURLConnection)root.openConnection();

if (rootCon.getResponseCode() == HttpURLConnection.HTTP_OK) {

String tempStr = "";

input = rootCon.getInputStream();

InputStreamReader isr = new InputStreamReader(input,

Charset.forName("UTF-8"));

in = new BufferedReader(isr);

while ((tempStr = in.readLine()) != null) {

content.append(tempStr);

}

return content.toString();

} else {

throw new Exception("interface exception for get Content ");

}

} catch (Exception e) {

e.printStackTrace();

} finally {

if(input != null ){

try {

input.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return content.toString();

}


   //接口URI调用 

    uri = "http://IP:PORT/Statistics.svc/Ajax/GetContractInfo?str_contract_code=xxxxx";

    getInfo(test.httpGetInfo(uri));   //接口JSON数据返回


数据处理  JSON 核心对MODEL模型的各个属性进行遍历赋值 并封装为 LIST列表

//核心处理函数 参数: builder 为字符串对象   , 反射核心 

public static List getInfo(StringBuilder builder) {

                //com.alibaba.fastjson.JSONObject  对象说明

JSONObject jobj = JSON.parseObject(builder.toString());

JSONObject model = jobj.getJSONObject("d");

List<ModelInfo> listVolume = new ArrayList<ModelInfo>();

ContractBakInfo v = null;

try {

Class c = Class.forName("com.model.ModelInfo");

c.newInstance(); // 生成类的对象, 并赋值

// 为整个对象 的每个属性赋值

Field[] fields = c.getDeclaredFields();

v = new ModelInfo();

for (Field field : fields) {

String fildname = field.getName();

Object fildVal = (Object) model.get(fildname);

// 调用getDeclaredField("name") 取得name属性对应的Field对象

Field f = c.getDeclaredField(field.getName());

// 取消属性的访问权限控制,即使private属性也可以进行访问。

f.setAccessible(true);

// // 调用set()方法给对应属性赋值。  

                                        //对不同的数据类型的数据进行处理   这里需要与接口的数据类型相对应

if("Contract_price".equalsIgnoreCase(field.getName()) ||"Contract_area".equalsIgnoreCase(field.getName())){

java.math.BigDecimal value = java.math.BigDecimal.valueOf(Double.valueOf(String.valueOf(fildVal)));

f.set(v, value); // 相当于obj.setName("lkl");

                                        //日期格式数据处理

}else if("Contract_date".equalsIgnoreCase(field.getName())){ 

String date = String.valueOf(fildVal);

date = date.substring(date.indexOf("(")+1,  date.indexOf("+"));

Date d = new Date(Long.valueOf(date));  

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

f.set(v, sdf.format(d)); 

}

else{

f.set(v, "null".equals(fildVal)?null:fildVal); // 相当于obj.setName("lkl");

}

}

// 装入容器

listVolume.add(v);

} catch (Exception e) {

e.printStackTrace();

}

return listVolume;

}



如有疑问 请留言 欢迎提供建议

评论已有 0