Skip to main content
se añadieron 1881 caracteres en el cuerpo
Origen Enlace
Javier
  • 235
  • 2
  • 11
public class ParseGeojsonStream {
    
    private static final Logger log = LoggerFactory.getLogger(ParseGeojsonStream.class);
    
    private static Gson gson;
    
    private static List<String> listKeys;
    private static List<String> listTypes;
    
    @Bean
    public static ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        return mapper;
    }
    
    public static void parseJson(final String name, final TableGeoJsonStream tableStream, final InputStream is) throws IOException {

        GsonBuilder builder = new GsonBuilder();
        builder.serializeNulls();
        gson = builder.create();
        
        // Create and configure an ObjectMapper instance
        ObjectMapper mapper = objectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        
        // Create a JsonParser instance
        try (JsonParser jsonParser = mapper.getFactory().createParser(is)) {

            // Check the first token
            if (jsonParser.nextToken() != JsonToken.START_OBJECT) {
                throw new IllegalStateException("Expected content to be an object");
            }
            
            JsonParser featureJson = findFeaturesToken(jsonParser);
            
            if (featureJson == null) {
                throw new IOException("Expected content to be not null");
            }
            
            if (featureJson.nextToken() != JsonToken.START_ARRAY) {
                throw new IOException("Expected content to be an array");
            }
            
            
            tableStream.createTable(name);
            
            List<Feature> features = new ArrayList<Feature>();
            
            boolean firstFeature = true;
            // Iterate over the tokens until the end of the array
            while (featureJson.nextToken() != JsonToken.END_ARRAY) {
                // Read a contact instance using ObjectMapper and do something with it
                // De 50 en 50
                Feature feature = mapper.readValue(featureJson, Feature.class);
                features.add(feature);
                
                if (firstFeature) {
                    firstFeature = false;
                    // create table
                    Object featurePropertiesgetKeyAndTypeOfProperties((Map<String, =?>) feature.getProperties());
                    log.infocreateTableWithFields("Properties: " +tableStream, featureProperties.toString()name);
                }
                
                
//                if (features.size() == 50) {
//                    generateSQLValues(tableStream, features);
//                    features.clear();
//                }
            }
            
            // Añadimos el resto que sobra
//            if (features.size() > 0) {
//                generateSQLValues(tableStream, features);
//                features.clear();
//            }
            
        }
    }
    
    private static void getKeyAndTypeOfProperties(Map<String, ?> objectproperties) {
        listKeys = new ArrayList<String>();
        listTypes = new ArrayList<String>();
        
        Iterator<String> it = objectproperties.keySet().iterator();
        while(it.hasNext()){
            String key = (String) it.next();
            log.info("KEY: "+ key);
            listKeys.add(key);
            listTypes.add(getTypeOfKey(key, objectproperties.get(key)));
        }
    }
    
    private static String getTypeOfKey(String key, Object value) {
        String type = "";
        if (value == null) {
            if (key.toLowerCase().contains("id")) {
                type = "int8";
            } else if (key.toLowerCase().contains("fecha") || key.toLowerCase().contains("date")) {
                type = "date";
            } else {
                type = "text";              
            }
        } else if (value instanceof String) {
            type = "text";
        } else if (value instanceof Boolean) {
            type = "boolean";
        } else if (value instanceof Double) {
            type = "decimal";
        } else if (value instanceof Integer) {
            type = "int8";
        } else if (value instanceof Date) {
            type = "date";
        } else {
            type = "text";
        }
        return type;
    }
    
    private static JsonParser findFeaturesToken(JsonParser jsonParser) throws IOException, NullPointerException {
        JsonParser json = jsonParser;
        try {
            while(true) {
                String text = json.getText().toLowerCase();
                if ( text.equalsIgnoreCase(GEOJSONConstants.ApiJSON.FEATURES.toLowerCase()) ) {
                    return json;
                }
                json.nextToken();               
            }           
        } catch(NullPointerException e) {
            return null;
        }
    }
    
    private static void createTablecreateTableWithFields(final TableGeoJsonStream tableStream, final String nameTablename) {
        String SQLkeys = "CREATE"";
 TABLE IF NOT EXISTS " + nameTable for (int i=0; i<listKeys.size(); i++) {
            keys += listKeys.get(i) + " " + listTypes.get(i) table_id+ SERIAL", aquí";
 van las keys de las propiedades  ,}
 geom       keys = keys + "geom geometry(GeometryZ,4326), primary key (table_id));";";
    
       tableStream.createTableWithColumnsDinamically(name, keys);
    }
    
    private static void generateSQLValues(final TableGeoJsonStream tableStream, final List<Feature> features) {
        String SQL_VALUESSQL = "INSERT INTO " + tableStream.getCheckedNameTable(); 
//      String SQL = "INSERT INTO " + checkedNameTable + " ( properties, geom ) VALUES ( '" + property + "', ST_Force3D(ST_SetSRID(ST_GeomFromGeoJSON('" + geometry + "'), 4326) ));"; 
        String keys = "";
        for (int i=0; i<listKeys.size(); i++) {
            keys += listKeys.get(i) + ", ";
        }
        SQL += " ( " + keys + " geom ) VALUES ";
        
        String allValues = "";
        for (int i=0; i<features.size(); i++) {
            ifString (features.sizevalues = " () -";
 1 == i) {
        Feature feature = features.get(i);
     SQL_VALUES += "( '" + gson.toJson(features.get(i).getProperties()) + "'Map<String, ST_Force3D(ST_SetSRID(ST_GeomFromGeoJSON('"?> +properties gson.toJson(features.get= (iMap<String, ?>) feature.getGeometrygetProperties()) + "'),;
 4326) ) );";
         for (int j=0; }j<listKeys.size(); elsej++) {
                SQL_VALUESvalues += "( '" + gson.toJson(featuresproperties.get(i)listKeys.getPropertiesget(j)) + "'", ST_Force3D(ST_SetSRID(ST_GeomFromGeoJSON('""; + gson.toJson(features.get(i).getGeometry()) + "'), 4326) ) ), ";   
            }
            // añadir campo geometria
            values += feature.getGeometry() + " ";
            values = (i == features.size()) ? values + " ) " : values + " ), ";             
            allValues += values;
        }   
        log.info("All Values: " + allValues);
        
        
        
        
//      String SQL_BEGIN = "INSERT INTO " + tableStream.getCheckedNameTable() + " ( keys de las propiedades, geom ) VALUES ";
  //      String SQL = SQL_BEGIN + SQL_VALUES;
  //      tableStream.insertMultipleRows(SQL);
    }
    

}

public class ParseGeojsonStream {
    
    private static final Logger log = LoggerFactory.getLogger(ParseGeojsonStream.class);
    
    private static Gson gson;
    
    @Bean
    public static ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        return mapper;
    }
    
    public static void parseJson(final String name, final TableGeoJsonStream tableStream, final InputStream is) throws IOException {

        GsonBuilder builder = new GsonBuilder();
        builder.serializeNulls();
        gson = builder.create();
        
        // Create and configure an ObjectMapper instance
        ObjectMapper mapper = objectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        
        // Create a JsonParser instance
        try (JsonParser jsonParser = mapper.getFactory().createParser(is)) {

            // Check the first token
            if (jsonParser.nextToken() != JsonToken.START_OBJECT) {
                throw new IllegalStateException("Expected content to be an object");
            }
            
            JsonParser featureJson = findFeaturesToken(jsonParser);
            
            if (featureJson == null) {
                throw new IOException("Expected content to be not null");
            }
            
            if (featureJson.nextToken() != JsonToken.START_ARRAY) {
                throw new IOException("Expected content to be an array");
            }
            
            
            tableStream.createTable(name);
            
            List<Feature> features = new ArrayList<Feature>();
            
            boolean firstFeature = true;
            // Iterate over the tokens until the end of the array
            while (featureJson.nextToken() != JsonToken.END_ARRAY) {
                // Read a contact instance using ObjectMapper and do something with it
                // De 50 en 50
                Feature feature = mapper.readValue(featureJson, Feature.class);
                features.add(feature);
                
                if (firstFeature) {
                    firstFeature = false;
                    // create table
                    Object featureProperties = feature.getProperties();
                    log.info("Properties: " + featureProperties.toString());
                }
                
                
//              if (features.size() == 50) {
//                  generateSQLValues(tableStream, features);
//                  features.clear();
//              }
            }
            
            // Añadimos el resto que sobra
//          if (features.size() > 0) {
//              generateSQLValues(tableStream, features);
//              features.clear();
//          }
            
        }
    }
    
    private static JsonParser findFeaturesToken(JsonParser jsonParser) throws IOException, NullPointerException {
        JsonParser json = jsonParser;
        try {
            while(true) {
                String text = json.getText().toLowerCase();
                if ( text.equalsIgnoreCase(GEOJSONConstants.ApiJSON.FEATURES.toLowerCase()) ) {
                    return json;
                }
                json.nextToken();               
            }           
        } catch(NullPointerException e) {
            return null;
        }
    }
    
    private static void createTable(final TableGeoJsonStream tableStream, final String nameTable) {
        String SQL = "CREATE TABLE IF NOT EXISTS " + nameTable + " ( table_id SERIAL, aquí van las keys de las propiedades  , geom geometry(GeometryZ,4326), primary key (table_id));";
    
        
    }
    
    private static void generateSQLValues(final TableGeoJsonStream tableStream, final List<Feature> features) {
        String SQL_VALUES = ""; 
        for (int i=0; i<features.size(); i++) {
            if (features.size() - 1 == i) {
                SQL_VALUES += "( '" + gson.toJson(features.get(i).getProperties()) + "', ST_Force3D(ST_SetSRID(ST_GeomFromGeoJSON('" + gson.toJson(features.get(i).getGeometry()) + "'), 4326) ) );";
            } else {
                SQL_VALUES += "( '" + gson.toJson(features.get(i).getProperties()) + "', ST_Force3D(ST_SetSRID(ST_GeomFromGeoJSON('" + gson.toJson(features.get(i).getGeometry()) + "'), 4326) ) ), ";
            }
        }
        
        String SQL_BEGIN = "INSERT INTO " + tableStream.getCheckedNameTable() + " ( keys de las propiedades, geom ) VALUES ";
        String SQL = SQL_BEGIN + SQL_VALUES;
        tableStream.insertMultipleRows(SQL);
    }
    

}

public class ParseGeojsonStream {
    
    private static final Logger log = LoggerFactory.getLogger(ParseGeojsonStream.class);
    
    private static Gson gson;
    
    private static List<String> listKeys;
    private static List<String> listTypes;
    
    @Bean
    public static ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        return mapper;
    }
    
    public static void parseJson(final String name, final TableGeoJsonStream tableStream, final InputStream is) throws IOException {

        GsonBuilder builder = new GsonBuilder();
        builder.serializeNulls();
        gson = builder.create();
        
        // Create and configure an ObjectMapper instance
        ObjectMapper mapper = objectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        
        // Create a JsonParser instance
        try (JsonParser jsonParser = mapper.getFactory().createParser(is)) {

            // Check the first token
            if (jsonParser.nextToken() != JsonToken.START_OBJECT) {
                throw new IllegalStateException("Expected content to be an object");
            }
            
            JsonParser featureJson = findFeaturesToken(jsonParser);
            
            if (featureJson == null) {
                throw new IOException("Expected content to be not null");
            }
            
            if (featureJson.nextToken() != JsonToken.START_ARRAY) {
                throw new IOException("Expected content to be an array");
            }
            
            List<Feature> features = new ArrayList<Feature>();
            
            boolean firstFeature = true;
            // Iterate over the tokens until the end of the array
            while (featureJson.nextToken() != JsonToken.END_ARRAY) {
                // Read a contact instance using ObjectMapper and do something with it
                // De 50 en 50
                Feature feature = mapper.readValue(featureJson, Feature.class);
                features.add(feature);
                
                if (firstFeature) {
                    firstFeature = false;
                    // create table
                    getKeyAndTypeOfProperties((Map<String, ?>) feature.getProperties());
                    createTableWithFields(tableStream, name);
                }
                
                
                if (features.size() == 50) {
                    generateSQLValues(tableStream, features);
                    features.clear();
                }
            }
            
            // Añadimos el resto que sobra
            if (features.size() > 0) {
                generateSQLValues(tableStream, features);
                features.clear();
            }
            
        }
    }
    
    private static void getKeyAndTypeOfProperties(Map<String, ?> objectproperties) {
        listKeys = new ArrayList<String>();
        listTypes = new ArrayList<String>();
        
        Iterator<String> it = objectproperties.keySet().iterator();
        while(it.hasNext()){
            String key = (String) it.next();
            log.info("KEY: "+ key);
            listKeys.add(key);
            listTypes.add(getTypeOfKey(key, objectproperties.get(key)));
        }
    }
    
    private static String getTypeOfKey(String key, Object value) {
        String type = "";
        if (value == null) {
            if (key.toLowerCase().contains("id")) {
                type = "int8";
            } else if (key.toLowerCase().contains("fecha") || key.toLowerCase().contains("date")) {
                type = "date";
            } else {
                type = "text";              
            }
        } else if (value instanceof String) {
            type = "text";
        } else if (value instanceof Boolean) {
            type = "boolean";
        } else if (value instanceof Double) {
            type = "decimal";
        } else if (value instanceof Integer) {
            type = "int8";
        } else if (value instanceof Date) {
            type = "date";
        } else {
            type = "text";
        }
        return type;
    }
    
    private static JsonParser findFeaturesToken(JsonParser jsonParser) throws IOException, NullPointerException {
        JsonParser json = jsonParser;
        try {
            while(true) {
                String text = json.getText().toLowerCase();
                if ( text.equalsIgnoreCase(GEOJSONConstants.ApiJSON.FEATURES.toLowerCase()) ) {
                    return json;
                }
                json.nextToken();               
            }           
        } catch(NullPointerException e) {
            return null;
        }
    }
    
    private static void createTableWithFields(final TableGeoJsonStream tableStream, final String name) {
        String keys = "";
        for (int i=0; i<listKeys.size(); i++) {
            keys += listKeys.get(i) + " " + listTypes.get(i) + ", ";
        }
        keys = keys + "geom geometry(GeometryZ,4326), primary key (table_id)";
        tableStream.createTableWithColumnsDinamically(name, keys);
    }
    
    private static void generateSQLValues(final TableGeoJsonStream tableStream, final List<Feature> features) {
        String SQL = "INSERT INTO " + tableStream.getCheckedNameTable(); 
//      String SQL = "INSERT INTO " + checkedNameTable + " ( properties, geom ) VALUES ( '" + property + "', ST_Force3D(ST_SetSRID(ST_GeomFromGeoJSON('" + geometry + "'), 4326) ));"; 
        String keys = "";
        for (int i=0; i<listKeys.size(); i++) {
            keys += listKeys.get(i) + ", ";
        }
        SQL += " ( " + keys + " geom ) VALUES ";
        
        String allValues = "";
        for (int i=0; i<features.size(); i++) {
            String values = " ( ";
            Feature feature = features.get(i);
            Map<String, ?> properties = (Map<String, ?>) feature.getProperties();
            for (int j=0; j<listKeys.size(); j++) {
                values += properties.get(listKeys.get(j)) + ", ";           
            }
            // añadir campo geometria
            values += feature.getGeometry() + " ";
            values = (i == features.size()) ? values + " ) " : values + " ), ";             
            allValues += values;
        }   
        log.info("All Values: " + allValues);
        
        
        
        
//      String SQL_BEGIN = "INSERT INTO " + tableStream.getCheckedNameTable() + " ( keys de las propiedades, geom ) VALUES ";
//      String SQL = SQL_BEGIN + SQL_VALUES;
//      tableStream.insertMultipleRows(SQL);
    }
Origen Enlace
Javier
  • 235
  • 2
  • 11

Cómo obtener las keys y values de un objeto y generar una tabla

Soy novata con springboot. Estoy usando una bbdd en postgressql con postgis.

En el código que muestro lo que hago es leer el inputStream de un fichero geojson y procesarlo.

Antes guardaba las propiedades del fichero geojson, que es un objeto con campos, como jsonb. Pero ahora quiero obtener cada una de las keys del objeto de las propiedades y su tipo para crear la tabla dinámicamente e insertar la información.

¿Cómo podría hacerlo?

public class ParseGeojsonStream {
    
    private static final Logger log = LoggerFactory.getLogger(ParseGeojsonStream.class);
    
    private static Gson gson;
    
    @Bean
    public static ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        return mapper;
    }
    
    public static void parseJson(final String name, final TableGeoJsonStream tableStream, final InputStream is) throws IOException {

        GsonBuilder builder = new GsonBuilder();
        builder.serializeNulls();
        gson = builder.create();
        
        // Create and configure an ObjectMapper instance
        ObjectMapper mapper = objectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        
        // Create a JsonParser instance
        try (JsonParser jsonParser = mapper.getFactory().createParser(is)) {

            // Check the first token
            if (jsonParser.nextToken() != JsonToken.START_OBJECT) {
                throw new IllegalStateException("Expected content to be an object");
            }
            
            JsonParser featureJson = findFeaturesToken(jsonParser);
            
            if (featureJson == null) {
                throw new IOException("Expected content to be not null");
            }
            
            if (featureJson.nextToken() != JsonToken.START_ARRAY) {
                throw new IOException("Expected content to be an array");
            }
            
            
            tableStream.createTable(name);
            
            List<Feature> features = new ArrayList<Feature>();
            
            boolean firstFeature = true;
            // Iterate over the tokens until the end of the array
            while (featureJson.nextToken() != JsonToken.END_ARRAY) {
                // Read a contact instance using ObjectMapper and do something with it
                // De 50 en 50
                Feature feature = mapper.readValue(featureJson, Feature.class);
                features.add(feature);
                
                if (firstFeature) {
                    firstFeature = false;
                    // create table
                    Object featureProperties = feature.getProperties();
                    log.info("Properties: " + featureProperties.toString());
                }
                
                
//              if (features.size() == 50) {
//                  generateSQLValues(tableStream, features);
//                  features.clear();
//              }
            }
            
            // Añadimos el resto que sobra
//          if (features.size() > 0) {
//              generateSQLValues(tableStream, features);
//              features.clear();
//          }
            
        }
    }
    
    private static JsonParser findFeaturesToken(JsonParser jsonParser) throws IOException, NullPointerException {
        JsonParser json = jsonParser;
        try {
            while(true) {
                String text = json.getText().toLowerCase();
                if ( text.equalsIgnoreCase(GEOJSONConstants.ApiJSON.FEATURES.toLowerCase()) ) {
                    return json;
                }
                json.nextToken();               
            }           
        } catch(NullPointerException e) {
            return null;
        }
    }
    
    private static void createTable(final TableGeoJsonStream tableStream, final String nameTable) {
        String SQL = "CREATE TABLE IF NOT EXISTS " + nameTable + " ( table_id SERIAL, aquí van las keys de las propiedades  , geom geometry(GeometryZ,4326), primary key (table_id));";
    
        
    }
    
    private static void generateSQLValues(final TableGeoJsonStream tableStream, final List<Feature> features) {
        String SQL_VALUES = ""; 
        for (int i=0; i<features.size(); i++) {
            if (features.size() - 1 == i) {
                SQL_VALUES += "( '" + gson.toJson(features.get(i).getProperties()) + "', ST_Force3D(ST_SetSRID(ST_GeomFromGeoJSON('" + gson.toJson(features.get(i).getGeometry()) + "'), 4326) ) );";
            } else {
                SQL_VALUES += "( '" + gson.toJson(features.get(i).getProperties()) + "', ST_Force3D(ST_SetSRID(ST_GeomFromGeoJSON('" + gson.toJson(features.get(i).getGeometry()) + "'), 4326) ) ), ";
            }
        }
        
        String SQL_BEGIN = "INSERT INTO " + tableStream.getCheckedNameTable() + " ( keys de las propiedades, geom ) VALUES ";
        String SQL = SQL_BEGIN + SQL_VALUES;
        tableStream.insertMultipleRows(SQL);
    }
    

}