微信工具类-----WechatMessageUtil

package com.sky.wechat.replyport;
import java.io.Writer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sky.wechat.replyport.model.Image;
import com.sky.wechat.replyport.model.News;
import com.sky.wechat.replyport.model.Text;
import com.sky.wechat.replyport.model.Tw;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;

import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

public class WechatMessageUtil {
	private final static Log log = LogFactory.getLog(WechatMessageUtil.class);
	
	/**将图文信息转换为xml
	 * @param n
	 * @return
	 */
	public static String news(News n) {
		xstream.alias("xml", News.class);
		xstream.alias("item", new Tw().getClass());
		System.out.println(">>>>>>>>"+xstream.toXML(n));
		return xstream.toXML(n);
	}
	
	/**将文本信息转化为xml
	 * @param t
	 * @return
	 */
	public static String text(Text t){
		xstream.alias("xml", Text.class);
		return xstream.toXML(t);
	}
	
	public static String image(Image i){
		xstream.alias("xml", Image.class);
		return xstream.toXML(i);
	}
	
	public static String getRelpay(Object o){
		if(o==null){
			return "";
		}else{
			if(o instanceof News){
				return news((News)o);
			}else if(o instanceof Text){
				return text((Text)o);
			}else if(o instanceof Image){
				return image((Image)o);
			}
		}
		return "";
	}
	
	private static  XStream xstream = new XStream(new XppDriver() {
		@Override
		public HierarchicalStreamWriter createWriter(Writer out) {
			return new PrettyPrintWriter(out) {
				// 对所有xml节点的转换都增加CDATA标记
				boolean cdata = true;
				@SuppressWarnings("unchecked")
				public void startNode(String name, Class clazz) {
					super.startNode(name);
				}

				@Override
				protected void writeText(QuickWriter writer, String text) {
					if (cdata) {
						writer.write("<![CDATA[");
						writer.write(text);
						writer.write("]]>");
					} else {
						writer.write(text);
					}
				}
			};
		}
	});

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值