Add objects of different classes to an ArrayList in Java

0

I have a problem adding objects to an arraylist. I have the following code line: List data = new ArrayList ();

to this list I want to approve the data of different classes, to later pass this list as a datasource to ireport.

            ContactoServer contactos=null;

            for(ContactoServer t : map.getContactoServer()){    
            contactos = new ContactoServer();
            contactos.setNmContacto(t.getNmContacto());
            contactos.setTelContacto(t.getTelContacto());
            contactos.setCelContacto(t.getCelContacto());
            contactos.setCorreoContacto( t.getCorreoContacto());
            data.add(contactos); 
            }

Here I can easily add contacts from the ContactServer class without any problem, but when I pass the following data from another "ListServer" class, the arrayList generates conflict when passing it as a datasource.

            ListServer lServidores = null;
            for(ListServer listServ : listarServidores.getListServer()){
                lServidores = new ListServer();
                lServidores.setNmIpnat(listServ.getNmIpnat());
                data.add(lServidores);

}

How do I add this to the data?

I hope you can help me, I pass the complete code:

@WebServlet (name="ServletJsonToMap", urlPatterns = {"/ ServletJsonToMap"}) public class ServletJsonToMap extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ParseException {
    response.setContentType("application/pdf");
    ServletOutputStream out = response.getOutputStream();

    //deserializo el json
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

    try
    {           
        JasperReport reporte = (JasperReport) JRLoader.loadObject(getServletContext().getRealPath("WEB-INF/prueba.jasper"));
        HashMap parametros = new HashMap();
       // mapeamos el json que se captura por URL https://api.myjson.com/bins/2y29g
       UserClass mapInf = mapper.readValue(new URL("https://api.myjson.com/bins/2fw0y"), UserClass.class);
       UserClass listarServidores = mapper.readValue(new URL("https://api.myjson.com/bins/2fw0y"), UserClass.class);
       Server map = mapper.readValue(new URL("https://api.myjson.com/bins/2fw0y"), Server.class);           

        List data = new ArrayList();


        //Pasamos los parametros a mostrar - Información general de la empresa 
          if(mapInf != null){
          parametros.put("infoEmpNmEmpresa", mapInf.getInfoEmpNmEmpresa());
          parametros.put("tipoIdentificacionEmp", mapInf.getTipoIdentificacionEmp());
          parametros.put("infoEmpNumeroIdentificacion", mapInf.getInfoEmpNumeroIdentificacion());            
          parametros.put("infoEmpDireccion", mapInf.getInfoEmpDireccion());
          parametros.put("departamento", mapInf.getDepartamento());
          parametros.put("ciudad", mapInf.getCiudad());
          parametros.put("infoEmpTelefono", mapInf.getInfoEmpTelefono());
          parametros.put("infoEmpCel", mapInf.getInfoEmpCel());
          parametros.put("infoEmpCorreo", mapInf.getInfoEmpCorreo());              
          parametros.put("infoLegalNmEmpresa", mapInf.getInfoLegalNmEmpresa());
          parametros.put("tipoIdentificacionLegal", mapInf.getTipoIdentificacionLegal());
          parametros.put("infoLegalNumeroIden", mapInf.getInfoLegalNumeroIden());
          parametros.put("infoLegalDireccion", mapInf.getInfoLegalDireccion());
          parametros.put("infoLegalTelefono", mapInf.getInfoLegalTelefono());
          parametros.put("infoLegalCel", mapInf.getInfoLegalCel());
          parametros.put("infoLegalCorreo", mapInf.getInfoLegalCorreo());              
          parametros.put("tipoCuenta", mapInf.getTipoCuenta());
          parametros.put("infoComiNumCta", mapInf.getInfoComiNumCta());
          parametros.put("txtArea", mapInf.getTxtArea());

          //Parametros envio y recepcion pagos
          parametros.put("formatoTipoPago", mapInf.getFormatoTipoPago());
          parametros.put("formatoTipoPagoRecp", mapInf.getFormatoTipoPagoRecp());
          parametros.put("tipoRespuesta", mapInf.getTipoRespuesta());
          parametros.put("radioRes", mapInf.getRadioRes());
          parametros.put("radioResCuentas", mapInf.getRadioResCuentas());
          parametros.put("checkConsolidadoPagos", mapInf.getCheckConsolidadoPagos());
          parametros.put("selectRecep", mapInf.getSelectRecep());
          parametros.put("radioResContenidoRespuesta", mapInf.getRadioResContenidoRespuesta());
          parametros.put("periosidadEnvio", mapInf.getPeriosidadEnvio());
          parametros.put("checkConsolidadoCuentas", mapInf.getCheckConsolidadoCuentas());
          parametros.put("nmMinutos", mapInf.getNmMinutos());
          parametros.put("minutosDos", mapInf.getMinutosDos());
          parametros.put("txtAreaObservaciones", mapInf.getTxtAreaObservaciones());

          for(CuentasEstado ce: mapInf.getCuentasEstados()){
              parametros.put("contenidoRespuesta", ce.getLabel());
             }
          for(ListaResp lr: mapInf.getListaResp()){
              parametros.put("listaRespuestas", lr.getLabel());
              }
        }

          // se recorre el objecto contacServer del Json
         if(map != null){
            ContactoServer contactos=null;
            for(ContactoServer t : map.getContactoServer()){    
                 contactos = new ContactoServer();
            contactos.setNmContacto(t.getNmContacto());
            contactos.setTelContacto(t.getTelContacto());
            contactos.setCelContacto(t.getCelContacto());
            contactos.setCorreoContacto( t.getCorreoContacto());
            data.add(contactos); 
            }

         } 
          //parametros servidor
         if(listarServidores != null){
              int contador=0;
            // se leen los contactos técnicos   
                ListServer lServidores = null;
            for(ListServer listServ : listarServidores.getListServer()){
                lServidores = new ListServer();
                lServidores.setNmIpnat(listServ.getNmIpnat());
                data.add(lServidores);


          contador ++;
          //data.add(contador);
         }
        }

        //Se muestra el reporte 
         JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, new JRBeanCollectionDataSource(data));
         //JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, new JREmptyDataSource());

        JRExporter exporter = new JRPdfExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
        exporter.exportReport();
    }
    catch (IOException | JRException e)
    {
    }

}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        processRequest(request, response);
    } catch (ParseException ex) {
       // Logger.getLogger(ServletJsonToMap.class.getName()).log(Level.SEVERE, null, ex);
    }
}

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        processRequest(request, response);
    } catch (ParseException ex) {
        Logger.getLogger(ServletJsonToMap.class.getName()).log(Level.SEVERE, null, ex);
    }
}

/**
 * Returns a short description of the servlet.
 *
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

private static class YAMLFactory extends JsonFactory {

    public YAMLFactory() {
    }
}

}

    
asked by Victor 16.11.2016 в 18:25
source

2 answers

0

It sends you an error because it is a different object than the one you have already saved, you should save it in two different lists, for example:

List<ContactoServer> data1 = new ArrayList();
List<ListServer> data2 = new ArrayList();
    
answered by 16.11.2016 / 19:55
source
0

You can do a interface and all your objects implement it

public interface IObject { }
public class ContactoServer implements IObject { }
public class ListServer implements IObject { }

List<IObject> lista = new ArrayList<IObject>();

The object lista of type List<Iobject> will accept any object that implements IObject

    
answered by 16.11.2016 в 20:04