有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Marshall/Unmarshall地图

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class ItemSubstitutionRequestDTO {
    
    public ItemSubstitutionRequestDTO()
    {
        
    }
    
    private List<Map<String,Integer>> substituteFor=new ArrayList<Map<String,Integer>>();
  private String orderId;
  
  public List<Map<String,Integer>> getSubstituteFor()
  {
      return substituteFor;
  }
  
  public void setSubstituteFor(List<Map<String,Integer>> substituteFor)
  {
      this.substituteFor = substituteFor;
  }
  
  public String getOrderId() {
      return orderId;
  }

  public void setOrderId(String orderId) {
      this.orderId = orderId;
  }
  
}

最终结果错误

java.util.Map is an interface, and JAXB can't handle interfaces.

我无法让JaxB对Map实例进行marshall/unmarshall处理。我还尝试了其他注释,发现这是解决上述错误的可能方法之一,但没有任何效果

下面是来自UI端的输入json

{ "itemSubstitutionRequestDTO": { "substituteFor": [{"41712":2}], "orderId": "1073901", } }


共 (1) 个答案

  1. # 1 楼答案

    您没有编写XML内容在 <substituteFor>元素看起来像。 因此,我假设如下:

    <itemSubstitutionRequestDTO>
        <substituteFor>
            <item>
                <key>x</key>
                <value>23</value>
            </item>
            <item>
                <key>y</key>
                <value>3</value>
            </item>
        </substituteFor>
        <orderId>abc</orderId>
    </itemSubstitutionRequestDTO>
    

    正如JAXB错误消息已经告诉您的那样, 它无法处理具有< >之间接口的类型, 比如你的List<Map<String,Integer>>。 但是,它可以处理具有介于< >之间的普通类的类型, 像List<SubstitutionMap>

    因此,第一步是重写ItemSubstitutionRequestDTO类 因此它不使用List<Map<String,Integer>>,而是使用List<SubstitutionMap>。 您需要自己编写SubstitutionMap类(不是接口)。 但它可以非常简单:

    public class SubstitutionMap extends HashMap<String, Integer> {
    }
    

    现在JAXB不再抛出错误,但它仍然不知道如何封送/取消封送aSubstitutionMap。 因此,您需要为它编写一个^{}。 让我们称之为SubstitutionMapAdapter。 为了让JAXB知道这个适配器,需要对substituteFor进行注释 属性在ItemSubstitutionRequestDTO类中使用:

    @XmlJavaTypeAdapter(SubstitutionMapAdapter.class)
    

    适配器的工作是从SubstitutionMap进行实际转换 到SubstitutionMapElement数组,反之亦然。 然后JAXB可以自己处理SubstitutionMapElement数组

    public class SubstitutionMapAdapter extends XmlAdapter<SubstitutionMapElement[], SubstitutionMap> {
    
        @Override
        public SubstitutionMap unmarshal(SubstitutionMapElement[] elements) {
            if (elements == null)
                return null;
            SubstitutionMap map = new SubstitutionMap();
            for (SubstitutionMapElement element : elements)
                map.put(element.getKey(), element.getValue());
            return map;
        }
    
        @Override
        public SubstitutionMapElement[] marshal(SubstitutionMap map) {
            // ... (left to you as exercise)
        }
    }
    

    SubstitutionMapElement只是一个键和值的简单容器

    @XmlAccessorType(XmlAccessType.FIELD)
    public class SubstitutionMapElement {
    
        private String key;
        private int value;
        
        // ... constructors, getters, setters omitted here for brevity
    }