Как получить доступ к моим данным GeoJSON после десериализации их в объект с помощью Джексона - PullRequest
2 голосов
/ 16 октября 2019

Я создал объект Java путем десериализации файла JSON с использованием Jackson. Я хочу отобразить данные в предоставленном шаблоне карты, но я не уверен, как получить к ним доступ.

Ниже приведен код и файл JSON. Я на правильном пути? Кто-то посоветовал мне получить доступ к объекту, если я использую этот класс Feature в методе main. Что-то вроде ex: Feature obj = new Feature();, а затем получить доступ к любой из переменных, используя obj.getType(). На самом деле я хочу получить доступ ко всему файлу, чтобы он отображал данные на WorldWind Map.

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [102.0, 0.6]
            },
            "properties": {
                "prop0": "value0"
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "LineString",
                "coordinates": [
                    [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
                ]
            },
            "properties": {
                "prop1": 0.0,
                "prop0": "value0"
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Polygon",
                "coordinates": [
                    [
                        [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0],
                        [100.0, 0.0]
                    ]
                ]
            },
            "properties": {
                "prop1": {
                    "this": "that"
                },
                "prop0": "value0"
            }
        }
    ]
}

и вот мой код:

public class NetworkVisualizer extends ApplicationTemplate {

  public static class AppFrame extends ApplicationTemplate.AppFrame {

    public AppFrame() {
      super(true, true,
            false);

      // Size the World Window to take up the space typically used by the layer panel.
      Dimension size = new Dimension(1400, 800);
      this.setPreferredSize(size);
      this.pack();
      WWUtil.alignComponent(null, this, AVKey.CENTER);

      makeMenu(this);
    }


    protected static void makeMenu(final AppFrame appFrame) {
      final JFileChooser fileChooser = new JFileChooser();
      fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("JSON File", "json", "json"));

      JMenuBar menuBar = new JMenuBar();
      appFrame.setJMenuBar(menuBar);
      JMenu fileMenu = new JMenu("File");
      menuBar.add(fileMenu);

      JMenuItem openFileMenuItem = new JMenuItem(new AbstractAction("Open File...") {
        public void actionPerformed(ActionEvent actionEvent) {
          try {
            int status = fileChooser.showOpenDialog(appFrame);
            if (status == JFileChooser.APPROVE_OPTION) {

              //TODO Likely need to start here when handling parsing of GeoJSON!

              @JsonInclude(JsonInclude.Include.NON_NULL)
              @JsonPropertyOrder({
                      "type",
                      "geometry",
                      "properties"
              })
              class Feature {

                @JsonProperty("type")
                private String type;
                @JsonProperty("geometry")
                private Geometry geometry;
                @JsonProperty("properties")
                private Properties properties;
                @JsonIgnore
                private Map<String, Object> additionalProperties = new HashMap<String, Object>();

                @JsonProperty("type")
                public String getType() {
                  return type;
                }

                @JsonProperty("type")
                public void setType(String type) {
                  this.type = type;
                }

                @JsonProperty("geometry")
                public Geometry getGeometry() {
                  return geometry;
                }

                @JsonProperty("geometry")
                public void setGeometry(Geometry geometry) {
                  this.geometry = geometry;
                }

                @JsonProperty("properties")
                public Properties getProperties() {
                  return properties;
                }

                @JsonProperty("properties")
                public void setProperties(Properties properties) {
                  this.properties = properties;
                }

                @JsonAnyGetter
                public Map<String, Object> getAdditionalProperties() {
                  return this.additionalProperties;
                }

                @JsonAnySetter
                public void setAdditionalProperty(String name, Object value) {
                  this.additionalProperties.put(name, value);
                }
              }
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      });

      fileMenu.add(openFileMenuItem);


    }




  }
  public static void main(String[] args) {

    final AppFrame af = (AppFrame) start("World Wind JSON Network Viewer", AppFrame.class);
  }
}

Здесь я получаю сообщение об ошибке

public static void main(String[] args) {

    final AppFrame af = (AppFrame) start("World Wind JSON Network Viewer", AppFrame.class);

    File selectedFile = jfc.getSelectedFile();
    ObjectMapper objectMapper = new ObjectMapper();
    FeatureCollection features = objectMapper.readValue(selectedFile, FeatureCollection.class);

  }

jfc говорит, что создание локальной переменной вызывает readValueнеобработанное исключение

1 Ответ

0 голосов
/ 17 октября 2019

Для работы с GeoJSON JSON полезными нагрузками вы можете использовать, например, библиотеку geojson-jackson , которая доступна в версии 1.12 . Чтобы использовать его, вам просто нужно добавить его в вашу Maven конфигурацию:

<dependency>
    <groupId>de.grundid.opendatalab</groupId>
    <artifactId>geojson-jackson</artifactId>
    <version>1.12</version>
</dependency>

Так как теперь вы можете прочитать вашу JSON конфигурацию, как показано ниже:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.geojson.FeatureCollection;

import java.io.File;
import java.io.IOException;

public class GeoJSON {

    public static void main(String[] args) throws IOException {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper objectMapper = new ObjectMapper();
        FeatureCollection features = objectMapper.readValue(jsonFile, FeatureCollection.class);
        features.forEach(System.out::println);
    }
}

Над отпечатками кода:

Feature{properties={prop0=value0}, geometry=Point{coordinates=LngLatAlt{longitude=102.0, latitude=0.6, altitude=NaN}} GeoJsonObject{}, id='null'}
Feature{properties={prop1=0.0, prop0=value0}, geometry=LineString{} MultiPoint{} Geometry{coordinates=[LngLatAlt{longitude=102.0, latitude=0.0, altitude=NaN}, LngLatAlt{longitude=103.0, latitude=1.0, altitude=NaN}, LngLatAlt{longitude=104.0, latitude=0.0, altitude=NaN}, LngLatAlt{longitude=105.0, latitude=1.0, altitude=NaN}]} GeoJsonObject{}, id='null'}
Feature{properties={prop1={this=that}, prop0=value0}, geometry=Polygon{} Geometry{coordinates=[[LngLatAlt{longitude=100.0, latitude=0.0, altitude=NaN}, LngLatAlt{longitude=101.0, latitude=0.0, altitude=NaN}, LngLatAlt{longitude=101.0, latitude=1.0, altitude=NaN}, LngLatAlt{longitude=100.0, latitude=1.0, altitude=NaN}, LngLatAlt{longitude=100.0, latitude=0.0, altitude=NaN}]]} GeoJsonObject{}, id='null'}

Как видите, у вас есть доступ к каждому свойству очень структурированным способом. Вам не нужно создавать собственную POJO, просто используйте уже реализованную и протестированную модель POJO. В вашем примере вы можете сделать это следующим образом:

if (status == JFileChooser.APPROVE_OPTION) {
    File selectedFile = jfc.getSelectedFile();
    ObjectMapper objectMapper = new ObjectMapper();
    FeatureCollection features = objectMapper.readValue(selectedFile, FeatureCollection.class);
}

См. Также:

...