es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Mostrar JSON en TableView

Estoy desarrollando un editor genérico para arrays JSON utilizando JavaFX. El despliegue en la tabla será de una manera en la que las columnas serán las llaves y los valores en las filas serán más descriptivos. Puede haber un número diferente de llaves en un JSONObject.

JSON en la forma:

"[{\"key1\": 1, \"key2\": 2}, {\"key1\": 3, \"key2\": 4}]"

Debe lucir así:

key1 key2
1 2
3 4

¿Tienes alguna sugerencia?

Tags:  , , ,

Answer

  1. Avatar for davy.ai

    Una forma de lograr esto es utilizando el TableView de JavaFX. Puedes crear una clase POJO para mapear los datos JSON, teniendo las claves como atributos. Después, puedes poblar el TableView con una lista de objetos de esta clase POJO.

    Aquí tienes un ejemplo:

    import javafx.application.Application;
    import javafx.beans.property.SimpleIntegerProperty;
    import javafx.beans.property.SimpleStringProperty;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.scene.Scene;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TableView;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    public class JsonTableView extends Application {
    
        // Clase POJO para mapear los datos JSON
        public static class JsonData {
            private SimpleIntegerProperty key1;
            private SimpleIntegerProperty key2;
    
            public JsonData(int key1, int key2) {
                this.key1 = new SimpleIntegerProperty(key1);
                this.key2 = new SimpleIntegerProperty(key2);
            }
    
            public int getKey1() {
                return key1.get();
            }
    
            public int getKey2() {
                return key2.get();
            }
        }
    
        @Override
        public void start(Stage primaryStage) {
            TableView<jsondata> tableView = new TableView<>();
    
            // Crear las columnas
            TableColumn<jsondata, integer=""> key1Col = new TableColumn<>("key1");
            key1Col.setCellValueFactory(cellData -> cellData.getValue().key1.asObject());
    
            TableColumn<jsondata, integer=""> key2Col = new TableColumn<>("key2");
            key2Col.setCellValueFactory(cellData -> cellData.getValue().key2.asObject());
    
            tableView.getColumns().addAll(key1Col, key2Col);
    
            // Parsear los datos JSON
            String jsonDataString = "[{\"key1\": 1, \"key2\": 2}, {\"key1\": 3, \"key2\": 4}]";
            JSONArray jsonArray = new JSONArray(jsonDataString);
    
            ObservableList<jsondata> data = FXCollections.observableArrayList();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                data.add(new JsonData(jsonObject.getInt("key1"), jsonObject.getInt("key2")));
            }
    
            tableView.setItems(data);
    
            VBox root = new VBox(tableView);
            primaryStage.setScene(new Scene(root, 300, 200));
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    Esto creará un TableView con dos columnas “key1” y “key2” y lo poblara con los datos del arreglo JSON. Si hay más claves en los objetos JSON, puedes agregar más columnas de la misma manera.</jsondata,></jsondata,>

Comments are closed.