package com.iamberry.wechat.tools;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;


public class MessageUtil {
	private final static XStream stream = new XStream(new DomDriver());
	
	/**
	 * 将一个XML格式的字符串转换为Java对象
	 * @param xml
	 * @param classT
	 * @return
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public static <T> Object xmlToBean(String xml, Class<T> classT) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		//创建XStream对象
//		XStream stream = new XStream(new DomDriver());
		//替换XML中的所有xml标签
		xml = xml.replaceAll("xml", classT.getName().toString());
		//通过Java反射创建对象
		Object object = classT.newInstance();
		//解析
		object = stream.fromXML(xml, object);
		//返回
		return object;
	}
	
	/**
	 * 将一个对象转换为一个XML格式的字符串
	 * @param object
	 * @return
	 */
	public static String beanToXML(Object object) {
		stream.alias("xml", object.getClass());
		return stream.toXML(object);
	}
	
	/**
	 * 转换JSON格式字符串为Bean
	 * @param json
	 * @param object
	 * @return
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	@SuppressWarnings("unchecked")
	public static Object jsonToBean(String json, @SuppressWarnings("rawtypes") Class classType) throws InstantiationException, IllegalAccessException {
		Gson gson = new Gson();
		//JsonElement root = gson.toJsonTree(str);
		Object object = classType.newInstance();
		object = gson.fromJson(json, classType);
		return object;
	}
	
	/**
	 * 将一个Object对象转换为一个String字符串
	 * @param object
	 * @return
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 */
	public static String objectToString(Object object) throws JsonGenerationException, JsonMappingException, IOException {
		// 对象转换字符串
		ObjectMapper objectMapper = new ObjectMapper();
		String resultStr = objectMapper.writeValueAsString(object);
		return resultStr;
	}
}
