[Web Service] 【解决】unable to marshal type "java.util.HashMap" as an element because ...异常简单解决办法

sa360430 2014-05-27

前几天玩rop,下载demo后,运行发现报错

 

Exception in thread "org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean#0-227" com.rop.RopException: com.rop.RopException: javax.xml.bind.MarshalException
 - with linked exception:
[com.sun.istack.internal.SAXException2: unable to marshal type "java.util.HashMap" as an element because it is missing an @XmlRootElement annotation]
	at com.rop.marshaller.MessageMarshallerUtils.getMessage(MessageMarshallerUtils.java:127)
	at com.rop.sample.SamplePreDoServiceEventListener.onRopEvent(SamplePreDoServiceEventListener.java:30)
	at com.rop.sample.SamplePreDoServiceEventListener.onRopEvent(SamplePreDoServiceEventListener.java:1)
	at com.rop.event.SimpleRopEventMulticaster$1.run(SimpleRopEventMulticaster.java:35)
.......

 

 

unable to marshal type "java.util.HashMap" as an element because it is missing an @XmlRootElement annotation  其实这句说的意思很明显HashMap没加上@XmlRootElement 注解,那就想办法加个注解咯 

 

我的做法是新加个继承HashMap的类,

 

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "HashMap")
public class ForHashMap<K,V>  extends HashMap<K,V>{
}

 ForHashMap有了 @XmlRootElement 注解然后改类MessageMarshallerUtils.java中方法getMessage

 

 

public static String getMessage(Object object, MessageFormat format) {
        if (object == null) {
            return "NONE MSG";
        }

        ForHashMap<Object,Object> map = new ForHashMap<Object,Object>();
        boolean ismap = false;
        if(object instanceof HashMap<?,?>){
        	ismap = true;
        	Map<Object,Object> _map = (Map<Object,Object>) object;
        	Iterator iter = _map.entrySet().iterator();
        	while (iter.hasNext()) {
        		Map.Entry entry = (Map.Entry) iter.next();
        		map.put(entry.getKey(),entry.getValue());
        	}
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
        try {
            if (format == MessageFormat.json) {
                JsonGenerator jsonGenerator = jsonObjectMapper.getJsonFactory().createJsonGenerator(bos, JsonEncoding.UTF8);
                jsonObjectMapper.writeValue(jsonGenerator, ismap?map:object);
            } else {
                xmlRopResponseMarshaller.marshaller(ismap?map:object, bos);
            }
            return bos.toString(UTF_8);
        } catch (Throwable e) {
            throw new RopException(e);
        } finally {
            try {
                bos.close();
            } catch (IOException ee) {
                logger.error("消息转换异常", ee);
            }
        }
    }

 

 

 以上是我的处理方法!!!

 

 

 

 

Global site tag (gtag.js) - Google Analytics