【反射】解析json 为例

本文介绍了一个使用Java反射机制解析特定格式的JSON字符串,并将其映射到Java实体类的方法。通过实例演示了如何针对不同类型的属性进行类型转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

好久没有弄过反射了,今天周末,想起来复习了下!

Person实体类

 

package com.masque.json;

import java.util.Date;
/**
* 
* @title: 实体信息
* @description: json对应封装的实体
* @className: Person.java
* @author: masque
* @createDate: 2013-7-27 
* @version: 1.0
*/
public class Person {
	private String name;
	private Date birthday;
	private Short sex;
	private Boolean isMarry;
	private Double high;
	private Float weight;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public Short getSex() {
		return sex;
	}
	public void setSex(Short sex) {
		this.sex = sex;
	}
	public Boolean getIsMarry() {
		return isMarry;
	}
	public void setIsMarry(Boolean isMarry) {
		this.isMarry = isMarry;
	}
	public Double getHigh() {
		return high;
	}
	public void setHigh(Double high) {
		this.high = high;
	}
	public Float getWeight() {
		return weight;
	}
	public void setWeight(Float weight) {
		this.weight = weight;
	}
	
}


解析过程

 

 

package com.masque.json;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 
 * @title: 反射
 * @description: 用来解析json并封装数据
 * @className: ObjToObj.java
 * @createDate: 2013-7-27
 * @version: 1.0
 */
public class ObjToObj {
	
	@SuppressWarnings("all")
	public static void main(String[] args) {
		//实体对应的字符串形式
		String personStr = "{'name':'xiao','birthday':'1989-02-22','sex':'1','isMarry':'false','high':'165.5','weight':'60.55'}"; 
		int flag = 1;
		//想将字符串解析成Map
		Map<String,String> inMap = new HashMap<String, String>();
		while(flag!=-1){
			flag = personStr.indexOf("','");
			if(flag==-1) continue;
			String pro = personStr.substring(1,flag+1);
			personStr = personStr.substring(flag+2);
			String [] pp = pro.replaceAll("'", "").split(":");
			inMap.put(pp[0], pp[1]);
		}
		
		Iterator<String> it = inMap.keySet().iterator();
		Class obj=null;
		Object a = null;
		try {
			obj = Class.forName("com.masque.json.Person");//反射得到类
			a = obj.newInstance();//实例化对象
		while (it.hasNext()) {
			String key = it.next();
			Method[] methods = obj.getMethods();//得到所有方法的对象数组
			String m = key.substring(0,1).toUpperCase()+key.substring(1);
			for (int i = 0; i < methods.length; i++) {
				if(methods[i].getName().equals("get"+m)){//get方法才有返回值!
					//得到返回值类型
					String returnType = methods[i].getReturnType().getSimpleName();
					System.out.println(returnType);
					Method method = null;
					//通过判断属性的类型来转换到对应的对象
					if(returnType.equals("Date")){
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
						method = obj.getDeclaredMethod("set"+m, Date.class);
						method.invoke(a,format.parse(inMap.get(key)));
					}
					if(returnType.equals("Short")){
						method = obj.getDeclaredMethod("set"+m, Short.class);
						method.invoke(a,Short.parseShort(inMap.get(key)));
					}
					if(returnType.equals("Boolean")){
						method = obj.getDeclaredMethod("set"+m, Boolean.class);
						method.invoke(a,Boolean.parseBoolean(inMap.get(key)));
					}
					if(returnType.equals("Double")){
						method = obj.getDeclaredMethod("set"+m, Double.class);
						method.invoke(a,Double.parseDouble(inMap.get(key)));
					}
					if(returnType.equals("Float")){
						method = obj.getDeclaredMethod("set"+m, Float.class);
						method.invoke(a,Float.parseFloat(inMap.get(key)));
					}
					if(returnType.equals("String")){
						method = obj.getDeclaredMethod("set"+m, String.class);
						method.invoke(a,inMap.get(key));
					}
				}
			}
		}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}catch (ClassNotFoundException e) {
			e.printStackTrace();
		}catch (InstantiationException e) {
			e.printStackTrace();
		}
		
		System.out.println(((Person)a).getName()+"省略。。。");
	}
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值