关于使用Xstream转换java对象时遇到的错误

开发中需要解析其他系统传的报文数据,需要转制定格式的内容.故需要在格式比较特殊的情况下需要自定义转换器.

xml格式如下, 是要对 <CrsrTg> 这个标签进行一定的调整转换

<TxnInfoTg>
       <MoreFTg>N</MoreFTg>
       <TotTxnMtchValTg>000001</TotTxnMtchValTg>
       <TotTxnSndValTg>000001</TotTxnSndValTg>
       <CrsrTg binaryEncoding="base64Binary">8PDw8PDw8PDw8Q==</CrsrTg>
</TxnInfoTg>

自定义的转换器如下 

public class ISMBinaryTypeConvertor implements Converter {

    /* (non-Javadoc)
     * @see com.thoughtworks.xstream.converters.ConverterMatcher#canConvert(java.lang.Class)
     */
    public boolean canConvert(final Class type) {
        return type.equals(ISMBinaryType.class);
    }

    /*
     * java bean convert to xml
     * */
    public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) {//TODO}
    }

    /*
     * xml convert to java bean
     * to get data by stream
     */
    public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
        ISMBinaryType resultBean = new ISMBinaryType();
        ISMBinaryEncodingType ismBinaryEncodingType = new ISMBinaryEncodingType();
        String content = reader.getValue();//get the value of the node
        //handler the base64 convert to byte[]
        resultBean.setContent(org.apache.tomcat.util.codec.binary.Base64.decodeBase64(content));
        ismBinaryEncodingType.setStringValue(reader.getAttribute("binaryEncoding"));
        ismBinaryEncodingType.setType(0);
        resultBean.setBinaryEncoding(ismBinaryEncodingType);
        return resultBean;
    }

}

在自定义转换器中遇到了如下错误:


cause-exception     : java.lang.IndexOutOfBoundsException
cause-message       : only START_TAG can have attributes END_TAG seen ...<CrsrTg binaryEncoding="base64Binary">8PDw8PDw8PDw8Q==</CrsrTg>... @88:94

是报我读取的这行标签找不到的属性。上网找了很久没有找到.

直到注意方法中的 reader 是一个流。那么就想到是否是读取的顺序问题,导致读的时候找不到某些指定值

随后调整了读取顺序

问题解决!

猜你喜欢

转载自blog.csdn.net/qq_40085888/article/details/81483483