java - 如何使用 javax.json 读取 JSON 数组

标签 java json

我有以下 Json 文件:

{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "PARK_ID": 393, "FACILITYID": 26249,  "coordinates": [ -75.73, 45.34 ] } },
{ "type": "Feature", "properties": { "PARK_ID": 161, "FACILITYID": 3510,  "coordinates": [ -75.73, 45.37 ] } },

我能够阅读第一行,“type”:“FeatureCollection”

但我不确定如何阅读“crs”和“features”。我试图使用“特征”中的坐标来制作一棵树。

到目前为止我的代码:

    import javax.json.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;


public class Preprocess {

    public static void main (String [] args){

        InputStream fis = null;
        try {
            fis = new FileInputStream("wadepools.json");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        JsonReader reader = Json.createReader(fis);
        JsonObject wadepool = reader.readObject();
        reader.

        System.out.println (wadepool.getString("features"));//if i put "type" here i get the output "FeatureCollection"
    }
    }

最好将其保留在 native json 库中,因为我没有任何 Maven 或 Gradle 的经验。

谢谢。

最佳答案

使用 javax.json 库

  1. 添加以下库作为依赖项或将它们添加到构建路径
    // https://mvnrepository.com/artifact/javax.json/javax.json-api
    implementation("javax.json:javax.json-api:1.1.4") // javax.json-api only contains the API (interfaces) and no implementation
    // https://mvnrepository.com/artifact/org.glassfish/javax.json
    implementation("org.glassfish:javax.json:1.1.4")// to get an implementation(but if your server comes with a pre-bundled implementation, you can skip this, but need for local development)

Ref
javax.json-api已弃用,建议使用jakarta.json-api

// https://mvnrepository.com/artifact/jakarta.json/jakarta.json-api
compile("jakarta.json:jakarta.json-api:2.0.0")
  • 正确的 JSON 文件,问题的 ] 和 } 不完整。
  • {
      "type": "FeatureCollection",
      "crs": {
        "type": "name",
        "properties": {
          "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
        }
      },
      "features": [
        {
          "type": "Feature",
          "properties": {
            "PARK_ID": 393,
            "FACILITYID": 26249,
            "coordinates": [
              -75.73,
              45.34
            ]
          }
        },
        {
          "type": "Feature",
          "properties": {
            "PARK_ID": 161,
            "FACILITYID": 3510,
            "coordinates": [
              -75.73,
              45.37
            ]
          }
        }
      ]
    }
    
  • 源代码
  • File fis = null;
    try {
        // provide a proper path to wadepools.json file
        fis = new File("./src/wadepools.json");
        JsonObject jsonObject;
        try (JsonReader reader = Json.createReader(new FileInputStream(fis))) {
            jsonObject = reader.readObject();
        }
        // since you know that features is an array of object, we will read it as JsonArray
        final JsonArray features = jsonObject.getJsonArray("features");
        System.out.println(features);
    
        // From json we know that features is array of objects and it has only 1 object, to read objects from array, we first locate it using index 0, we can iterate array and read objects too, but for simplicity we are targeting only 0th index
        final JsonObject object = features.getJsonObject(0);
        System.out.println(object.get("properties"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    /*output
    [{"type":"Feature","properties":{"PARK_ID":393,"FACILITYID":26249,"coordinates":[-75.73,45.34]}},{"type":"Feature","properties":{"PARK_ID":161,"FACILITYID":3510,"coordinates":[-75.73,45.37]}}]
    {"PARK_ID":393,"FACILITYID":26249,"coordinates":[-75.73,45.34]}
    */
    
    使用 jackson 库

    如果您不知道任何构建工具,您可以忽略此答案。 如果你学习一些构建工具,比如 Maven、Gradle 等,那就更好了。 https://maven.apache.org/ https://gradle.org/ 以下代码用于maven构建。 将以下依赖项添加到构建文件 pom.xml 中。

    pom.xml

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.0</version>
    </dependency>
    

    代码:

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.DeserializationFeature;
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class Preprocess {
    
        private static ObjectMapper MAPPER = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                
        public static void main (String [] args){
    
            File fis = null;
            try {
                // provide a proper path to wadepools.json file
                fis = new File("./src/wadepools.json");
                JsonNode jsonNode = MAPPER.readTree(fis);
                System.out.println(jsonNode.get("features"));
                System.out.println(jsonNode.get("features").get(0).get("properties"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (JsonProcessingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        }
    

    关于java - 如何使用 javax.json 读取 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49187938/

    相关文章:

    java - 如果需要复合索引,有没有办法将 Java Google App Engine SDK 的测试配置为失败?

    jquery元素无法从显示的json调用

    java - 从父节点创建的 Jackson 引用对象

    python - Pymongo/bson : Convert python. cursor.Cursor 对象到可序列化/JSON 对象

    json - 使用 axios 渲染 json 数据

    json - 如何在 Swagger 中引用另一个模型定义的 ID

    java - Spring 启动: Error creating bean with name 'springSecurityFilterChain'

    java - Hadoop Java 错误 : Exception in thread "main" java. lang.ClassNotFoundException : com. packt.ch3.etl.ParseWeblogs

    java - MaterialDatePicker 不适用于 Android

    java - 链式 API 调用中的 RxJava 错误处理