多层嵌套的Json字符串转成JavaBean实体对象

多层嵌套Json字符串转换为JavaBean。
  
   JavaBean1
     

public class RouterBusiness extends BaseBusiness {
	private static final long serialVersionUID = 1l;
	
	// 路由表示
	private String routerId;
	
	// 发送者队列
	private List sender = new ArrayList();
	
	// 接收者队列
	private List receiver = new ArrayList();

                   .........
                  get()和 set()方法略去

          }

     JavaBean2
 

public class MRPersistent{

	// sender name(receiver name)
	private String name;
	
	// 消息代理
	private MsgProxyPersistent msgProxy;
	
	// 类型
	private String type;
          .....get 、set方法
}
   JavaBean3
  
 
public class MsgProxyPersistent {
	

	// 解析器
	private String parse;
	
	// 适配器
	private String decorator;
	
	// 过滤器
	private String filter;
	
.........get  set方法

}

下面是将符合嵌套结构的Json字符串转换为JavaBean实体对象
  
	public RouterBusiness convertToBean(String jsonString){
		try {
			// 将json字符串转换为Router实体
			List routers = (List)JSONArray.toCollection(JSONArray.fromObject(jsonString));
			RouterBusiness rb = new RouterBusiness();
			for(Object router : routers){
				 rb = (RouterBusiness)JSONObject.toBean(JSONObject.fromObject(router),RouterBusiness.class);
				 List listReceiver = (List)rb.getReceiver();
				 List listSender = (List)rb.getSender();
				 List receivers = new  ArrayList();
				 List senders = new ArrayList() ;
				 for (Object sender : listSender) {
				     MRPersistent mrPersistent = (MRPersistent)JSONObject.toBean(JSONObject.fromObject(sender),MRPersistent.class);		
						MsgProxyPersistent msgProxyPersistent = (MsgProxyPersistent)JSONObject.toBean(JSONObject.fromObject(mrPersistent.getMsgProxy()),MsgProxyPersistent.class);						
						mrPersistent.setMsgProxy(msgProxyPersistent);;
						senders.add(mrPersistent);	
					}
				 
				 for(Object receiver : listReceiver){
					MRPersistent mrPersistent  = (MRPersistent)JSONObject.toBean(JSONObject.fromObject(receiver),MRPersistent.class);
					MsgProxyPersistent msgProxyPersistent = (MsgProxyPersistent)JSONObject.toBean(JSONObject.fromObject(mrPersistent.getMsgProxy()),MsgProxyPersistent.class);				
					mrPersistent.setMsgProxy(msgProxyPersistent);
					receivers.add(mrPersistent);
				 }
				 
				 rb.setReceiver(receivers);
				 rb.setSender(senders);
			}		
			return rb;
		} catch (Exception ex) {
			Log.error("convertToBean", ex, MonitorService.class);
			return null;
		}
	}

 
  
 
  

你可能感兴趣的:(java学习)