2

Estimad@s, Espero esten bien y sanos!! vengo a pedir ayuda con lo siguiente: tengo un archivo plano (interfaz) que tiene una matriz de datos posicional, y la estoy leyendo y cargando en un objeto Map, la lectura la hago gracias a un XML que tiene la informacion de lectura, posición de inicio, fin nombre y matriz padre.

He llegado al punto de poder leer y cargar los datos en un objeto Map y luego escribir un JSON, pero necesito darle niveles a este JSON.

cualquier recomendación y ayuda es bien recibida!!

Método que lee la interfaz de origen:

public static String leerInterfaz(BufferedReader interfazBR, Document xmlDoc,String interfazNombre) throws SAXException
    {    
    try { 
        Map<String, List<String>> parseoLinea = new HashMap<>();
        Map<String, String> parseoResultado = new HashMap<>();
        
        String line;  
        while((line=interfazBR.readLine())!=null)  
        {  
            String registroLocal =line.substring(0, 2);
            String registroDetalle =line.substring(1, 4);
            if(registroLocal.equals("1C")){
                registroLocal="registro";
                parseoLinea = leerXML(xmlDoc,registroLocal);
                if(parseoLinea!=null){
                    for(Map.Entry<String, List<String>> e : parseoLinea.entrySet()){
                        String valorTem = line.substring(Integer.parseInt(e.getValue().get(0))-1, 
                                Integer.parseInt(e.getValue().get(1))-1);
                        parseoResultado.put(e.getKey(),valorTem);
                     }
                    registroLocal="";
                    escribeJSON(parseoResultado,interfazNombre);
                    parseoLinea.clear(); 
                }
            }else{
                parseoLinea = leerXML(xmlDoc,registroDetalle);
                if(parseoLinea!=null){
                    parseoLinea.clear();
                }
                 
            }
            
        }
    }catch(IOException e)  
    {  
    }
    return null;
} 

**Metodo que carga la estructura de lectura en XML**

 public static Map leerXML(Document xmlDoc, String registro) throws SAXException, IOException
{
    Map<String, List<String>> parseoLinea = new HashMap<>();
    
    
    NodeList nodes = xmlDoc.getElementsByTagName(registro);

    Element element = (Element) nodes.item(0);
    if(element!=null){
    NodeList movieList = element.getElementsByTagName("campo");
    for (int i = 0; i < movieList.getLength(); i++) {
        List<String> atributos = new ArrayList<>();
        Element campo = (Element) movieList.item(i);
        atributos.add(campo.getAttributes().getNamedItem("inicio").getNodeValue());
        atributos.add(campo.getAttributes().getNamedItem("fin").getNodeValue());
        if(campo.getAttributes().getNamedItem("anidacion").getNodeValue().equals(null)){
            atributos.add(" ");
        }else{
            atributos.add(campo.getAttributes().getNamedItem("anidacion").getNodeValue());
        }
        parseoLinea.put(campo.getAttributes().getNamedItem("name").getNodeValue(), atributos);
    }

    return parseoLinea;
    }
    return null;
}

Método que escribe el JSON desde el Map

public static void escribeJSON(Map parseoResultado,String interfazNombre){
    FileWriter file = null;
    String jsonStr = JSONValue.toJSONString(parseoResultado); 
    
    try {

        // Constructs a FileWriter given a file name, using the platform's default charset
        file = new FileWriter("DIRECTORIO"+interfazNombre+".json");
        file.write(jsonStr);
        JSONLog("Archivo creado exitosamente");
        JSONLog("\nJSON Object: " + jsonStr);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {

        try {
            file.flush();
            file.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Ejemplo de interfaz de origen

1C  290720200000000000000000000000CERTIFI SOY UN REPORTE DE PRUEBAS SECURITY                          13247466-4  290720200030Banco Security      97053000-2                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
 D01PTMOS EN PESOS TASA FIJA CUADRO PAGO CLP                    000000472991290720200003986014188540000000000000000000000000000000000000000000000000000018310230000000000000000000000000000000000000000000000003985358999980000000000000000048000400360003      FIJA00000690000000000000000000000000001415285000000000000000                                                                                NoSi000000076047286000000000000000No                                                                                                                                                                                                                                                                                                                                                                                                                    
 D01PTMOS EN PESOS TASA FIJA CUADRO PAGO CLP                    000000472991290720200003986014188540000000000000000000000000000000000000000000000000000018310230000000000000000000000000000000000000000000000003985358999980000000000000000048000400360003      FIJA00000690000000000000000000000000001415285000000000000000                                                                                NoSi000000076047286000000000000000No     

                                                                                                                                                                                                                                                                                                                                                                                                           

XML con estructura de lectura

<?xml version="1.0" encoding="UTF-8"?>

1 respuesta 1

0

Bien, creo que al final lo solucione, probablemente no es la forma mas elegante pero funciona..

Primero Cree mi clase con la estructura principal y dentro de esta clase declaro un atributo con la estructura de otra clase (MontoAPagarOperacion), además de una lista de una tercera clase (MontoPagar).

public class CREALL2 {
    public String producto_servicio;
    public Long monto_ultimo_pago;
    public String moneda_operacion;
    public MontoAPagarOperacion monto_a_pagar_operacion;
    public List < MontoPagar > monto_a_pagar;
}
public class MontoAPagarOperacion {
    public String fecha;
    public BigDecimal total;
}
public class MontoPagar {
    public String fecha;
    public String monto;
}

con esto podemos administrar varios niveles y conjuntos de datos. además con el siguiente fragmento de código le cargo los datos a la estructura...

if (linea.get(0).toString().equals("D05")) {

    CREALL2 creditos = new CREALL2();
    MontoAPagarOperacion mntApagarOpe = new MontoAPagarOperacion();
    ArrayList listMontApagar = new ArrayList();

    Map < String,
    String > fechas = new HashMap < String,
    String > ();
    Map < String,
    Long > montos = new HashMap < String,
    Long > ();

    Iterator < ArrayList < ArrayList >> it1 = valores.iterator(); //aqui tengo los valores obtenidos gracias a la lectura de mi archivo
    while (it1.hasNext()) {
        ArrayList campo = it1.next();

        String parent = campo.get(4).toString();
        String name = campo.get(0).toString();
        String valor = campo.get(3).toString();

        Field field = CREALL2.class.getField(name);
        field.set(creditos, casteoClase.casteo(field.getType().getCanonicalName(), valor));

        Field field = MontoAPagarOperacion.class.getField(name);
        field.set(mntApagarOpe, casteoClase.casteo(field.getType().getCanonicalName(), valor));

        if (parent.equals("monto_a_pagar")) {
            if (name.substring(0, 5).equals("fecha")) {
                fechas.put(name, valor);
            } else {
                montos.put(name, Long.parseLong(valor));
            }
        }

        for (int i = 1; i <= 30; i++) {
            String iterador;
            if (i < 10) {
                iterador = "0" + i;
            } else {
                iterador = "" + i;
            }
            MontoPagar montPagar = new MontoPagar();
            montPagar.fecha = fechas.get("fecha" + iterador);
            montPagar.monto = montos.get("monto" + iterador);
            listMontApagar.add(montPagar);

            creditos.monto_a_pagar_operacion = mntApagarOpe;
            creditos.monto_a_pagar = listMontApagar;
            listCREALLDet.add(creditos);
        }
    }
}

Y en este segmento armo todo el documento y lo escribo en JSON, en el codigo oroginal son muchas mas clases que uso...

ProductosDetalle ProdDeta = new ProductosDetalle(listCREALLDet, listROTALLDet, listCTAALLDet);
ProductosResumen ProdResum = new ProductosResumen(listCREALL, listROTALL, listCTAALL);
ProductosSumaTotal ProdSumTot = new ProductosSumaTotal(listProdTotal);

PSR303Json = new Psr303(soli, ConCli, PfA, ProdResum, ProdDeta, ProdSumTot, listMandatosPa, listsegurosAsociados, listMorosidad, listGarantias);
Gson gson = new Gson();

String JsonName = interfazNombre + UUID.randomUUID().toString();
BufferedWriter writer = new BufferedWriter(new FileWriter(salidaPtah + "JSON" + JsonName + ".json"));
writer.write(gson.toJson(PSR303Json));
writer.close();

espero le sirva a alguien

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.