xstream 自定义 Converter

今天开发接口,遇到xml的格式比较特别大概格式为



  111111
  2222


  333
  4444


目前解决思路就是将R看做Map, C看做一个键值对。


  111111
  2222

理解为

{
    RECORD_ID: 111111,
    ORG_NO: 2222
}

定义一个JavaBean用来描述

@XStreamAlias("R")
@XStreamConverter(ResultConverter.class)
public class Result {
    
    public Map result = new HashMap();
    
    public void put(String key, Object val){
        result.put(key, val);
    }
    
    public void putAll(Map map) {
        result.putAll(map);
    }
    
    public Object get(String key) {
        return result.get(key);
    }
    
}

Converter

public class ResultConverter implements Converter {

    @Override
    public boolean canConvert(Class class_) {

        return "com.zhbr.ws.inf.yx.ws.entity.yxhc2.Result".equals(class_.getName());
    }

    @Override
    public void marshal(Object source, HierarchicalStreamWriter writer,
            MarshallingContext context) {
        Result r = (Result) source;
        Map result =  r.result;
        
        if(result.isEmpty()) return;
        
        for(Entry entry: result.entrySet()){
             writer.startNode("C");
             writer.addAttribute("N", entry.getKey());
             writer.setValue( StrUtil.toStr(entry.getValue()));             
             writer.endNode();
        }
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader,
            UnmarshallingContext context) {
        Result r = new Result();
        while (reader.hasMoreChildren()) {
            reader.moveDown();
            
            if ("C".equals(reader.getNodeName())) {
                String col = reader.getAttribute("N");              
                String val = reader.getValue();
                r.put(col, val);                
            }            
            reader.moveUp();
        }
        return r;
    }
}

测试

Result r = new Result();
r.put("RETURN_MSG", "xxx");
r.put("RETURN_FLAG", "0");

String xml = XmlUtil.toXml(r);
System.out.println(xml);

Result r2 = XmlUtil.toBean(xml, Result.class);
System.out.println(r2);

输出


  xxx
  0


RETURN_MSG: xxx,RETURN_FLAG: 0

你可能感兴趣的:(xstream 自定义 Converter)