如何编组Map <string,list <objects =“”>&gt;使用JAXB

时间:2015-10-17 19:53:14

标签: jaxb

我的代码中遇到了一个问题。

     @XmlRootElement
        @XmlAccessorType(XmlAccessType.FIELD) 
        @Entity 
        @NamedQueries({
        @NamedQuery(name = Parameter.FIND_ALL, query = "SELECT pm FROM Parameter pm")
    })
    public class Parameter implements Serializable {

        public static final String FIND_ALL = "Parameter.findAll";

            @XmlTransient
            private static final long serialVersionUID = 1L;
            @Id @GeneratedValue 
            private Long id;
            @XmlAttribute
            private String type;

            private String name; 

           //Setters and Getters
    }


     @XmlRootElement 
    @XmlAccessorType(XmlAccessType.FIELD)
    public class ParameterMap {
        private Map<String, List<Parameter>> parameterMap = new HashMap<String, List<Parameter>>();

        @XmlElement
        public Map<String, List<Parameter>> getParameterMap() {
            return parameterMap;
        }

        public void setParmeterMap(Map<String, List<Parameter>> parameterMap) {
            this.parameterMap = parameterMap;
        }

    }


    @Path("/parameter")
    public class ParameterRESTResource {

        @Inject
        private ParameterService paramService;

        /**
         *
         * @return
       @GET
        @Path("/")
        @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
        public List<Parameter> getAllParameters() throws JAXBException { 

           ParameterMap parameterMap = formatParameters(paramService.getAllParameters());

            JAXBContext jaxbContext = JAXBContext.newInstance(ParameterMap.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            jaxbMarshaller.marshal(parameterMap, System.out);
            jaxbMarshaller.marshal(parameterMap, new File("c:/temp/employees.xml"));

            return paramService.getAllParameters();
        }

         public ParameterMap formatParameters(List<Parameter> parameters)
        {
            HashMap<String, List<Parameter>> parameterMap = new HashMap<String, List<Parameter>>();
            ParameterMap paramMap = new ParameterMap();
            Parameter param = null;

            List<Parameter> list = null;

            for(int i=0;i<parameters.size();i++)
            {
                param = new Parameter();

                param = parameters.get(i);

                if(param.getType()!="text")
                {
                    list = new ArrayList<Parameter>();

                    if(parameterMap.containsKey(param.getName()))
                    {
                        list = parameterMap.get(param.getName());
                        list.add(param);
                    }
                    else {
                        list = new ArrayList<Parameter>();
                        list.add(param);
                    }

                }else {
                    list = new ArrayList<Parameter>();
                    list.add(param);

                }

                parameterMap.put(param.getName(), list);

            }

            paramMap.setParmeterMap(parameterMap);
            return paramMap;
        }

当我在本地(http://localhost:8080/home/rest/parameter/)上运行应用程序时,我收到以下错误。我的主要要求是显示地图&gt;在带有xml的UI上,包含所有信息。

  

org.jboss.resteasy.spi.UnhandledException:   com.sun.xml.bind.v2.runtime.IllegalAnnotationsException:1计数   IllegalAnnotationExceptions java.util.List是一个接口和JAXB   无法处理接口。这个问题与以下内容有关   location:位于私有java.util.Map的java.util.List中   nl.paston.insurance.product.model.ParameterMap.parameterMap at   nl.paston.insurance.product.model.ParameterMap       org.jboss.resteasy.core.ExceptionHandler.handleApplicationException(ExceptionHandler.java:76)       org.jboss.resteasy.core.ExceptionHandler.handleException(ExceptionHandler.java:212)       org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:149)       org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:372)       org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:179)       org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:220)       org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)       org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)       javax.servlet.http.HttpServlet.service(HttpServlet.java:790)       io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:86)       io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)       io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)       org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)       io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)       io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)       io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)       io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)       io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)       io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)       io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58)       io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:72)       io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)       io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76)       io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)       org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)       io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)       io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)       io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:282)       io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:261)       io.undertow.servlet.handlers.ServletInitialHandler.access $ 000(ServletInitialHandler.java:80)       io.undertow.servlet.handlers.ServletInitialHandler $ 1.handleRequest(ServletInitialHandler.java:172)       io.undertow.server.Connectors.executeRootHandler(Connectors.java:199)       io.undertow.server.HttpServerExchange $ 1.run(HttpServerExchange.java:774)       java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)       java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:617)       java.lang.Thread.run(Thread.java:745)

我希望我已提供所需的所有信息。在这个专家组中,请大家在这个问题上请帮助我。任何小的帮助对我都是最有帮助的。感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

包含集合作为值的地图有点棘手;您需要一个适配器和类来以JAXB可以处理的方式表示映射条目。

public class TrailActivity extends FragmentActivity implements ActionBar.TabListener {

SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
Intent intent;
Trail trail;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    intent = getIntent();
    setContentView(R.layout.trail_fracment_main);


    trail = intent.getParcelableExtra("trail");
    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setHomeButtonEnabled(true);
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
    }
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, tell the ViewPager to switch to the corresponding page.
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            InfoFragments infoFragments = new InfoFragments();
            infoFragments.setTrail(trail);
            Fragment fragment = infoFragments;
            return fragment;
        } else if (position == 1) {
            return new MapFragments();

        } else {
            return new WondersFragments();
        }

    }

    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
        }
        return null;
    }
}

适配器来回进行转换:


@XmlAccessorType(XmlAccessType.FIELD) 
public class ListOfEntry {
    @XmlElement
    private List list = new ArrayList();
    public List getList(){ return list; }
}

@XmlAccessorType(XmlAccessType.FIELD) 
public class Entry {
    @XmlElement
    private String key;
    @XmlElement
    private List list = new ArrayList();
    public String getKey(){ return key; }
    public void setKey( String value ){ key = value; }
    public List getList(){ return list; }
}

您必须在地图字段中添加注释:


public class Adapter 
extends XmlAdapter>> {
    @Override
    public Map> unmarshal(ListOfEntry loe)
        throws Exception {
        Map> map = new HashMap();
        for(Entry entry : loe.getList() ) {
            map.put(entry.getKey(), entry.getList() );
        }
        return map;
    }

    @Override
    public ListOfEntry marshal(Map> map)
        throws Exception {
        ListOfEntry loe = new ListOfEntry();
        for(Map.Entry> mapEntry : map.entrySet()) {
            Entry entry = new Entry();
            entry.setKey( mapEntry.getKey() );
            entry.getList().addAll( mapEntry.getValue() );
            loe.getList().add(entry);
        }
        return loe;
    }
}