首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用javax.json读取JSON中的数组

如何使用javax.json读取JSON中的数组
EN

Stack Overflow用户
提问于 2018-03-09 06:39:20
回答 2查看 1.6K关注 0票数 2

我有以下Json文件:

代码语言:javascript
复制
{
"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“和”功能“。我试着用“特征”中的坐标来做一棵树。

到目前为止,我的代码:

代码语言:javascript
复制
    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"
    }
    }

最好将它保存在本地json库中,因为我没有使用Maven或Gradle的经验。

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-09 06:53:18

您可以从数组中获取JSON obj。

杰森:

代码语言:javascript
复制
{
    "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]
            }
        }

    ]
}

爪哇:

代码语言:javascript
复制
    JSONArray jarray = (JSONArray) parser.parse(new FileReader("wadepools.json"));

      for (Object o : jarray )
      {
        JSONObject value= (JSONObject) o;

        String type= (String) value.get("type");
        System.out.println(type);

       JSONArray features= (JSONArray) value.get("features");
  for (Object features: features)
        {
          System.out.println(features+"");
        }

      }

希望这能帮上忙!

票数 -2
EN

Stack Overflow用户

发布于 2018-03-09 07:14:20

使用javax.json库

  1. 将下列库添加为依赖项或将它们添加到生成路径
代码语言:javascript
复制
    // 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

代码语言:javascript
复制
// https://mvnrepository.com/artifact/jakarta.json/jakarta.json-api
compile("jakarta.json:jakarta.json-api:2.0.0")
  1. 正确的JSON文件,问题是不完整的]和}。
代码语言:javascript
复制
{
  "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
        ]
      }
    }
  ]
}
  1. 源代码
代码语言:javascript
复制
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

代码语言:javascript
复制
<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>

代码:

代码语言:javascript
复制
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();
        }
    }
    }
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49187938

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档