微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从JsonNode提取数组?

如何解决如何从JsonNode提取数组?

我有以下输入内容

enter image description here

我要提取经纬度。我尝试了以下实现,但是收到 positionNode.get(i + 1).asDouble()

的空指针异常
private List<CoordinateBE> getCoordinate(final JsonNode positionNode) {
        
        final List<CoordinateBE> listofEntrances = new ArrayList<>();
        for (int i = 0; i < positionNode.size(); i = i + 2) {
            final CoordinateBE coordinateBE = new CoordinateBE();
            coordinateBE.setLatitude(positionNode.get(i).asDouble());
            coordinateBE.setLongitude(positionNode.get(i + 1).asDouble());  <--- Null Pointer Exception !!
            listofEntrances.add(coordinateBE);
        }
        return listofEntrances;
    }

如何解决上述实现?

解决方法

如果您使用的是com.fasterxml.jackson.databind.JsonNode,则可以按名称获取所需字段,而不用使用位置

  • positionlat.get(“ lat”)。asDouble()用于纬度
  • positionng。“(” lng“)。asDouble()for lng

这是Java中的示例

    @Test
    public void jsonNodeTest() throws Exception{
        JsonNode positionNode =  new ObjectMapper().readTree("{\"lat\":35.85,\"lng\":139.85}");
        System.out.println("Read simple object " + positionNode.get("lat").asDouble());
        System.out.println("Read simple object " +positionNode.get("lng").asDouble());

        ArrayNode positionNodeArray = (ArrayNode) new ObjectMapper().readTree("[" +
                "{\"lat\":35.85,\"lng\":139.85}," +
                "{\"lat\":36.85,\"lng\":140.85}" +
                "]");

        // With Stream API
        positionNodeArray.elements().forEachRemaining(jsonNode -> {
            System.out.println("Read in array " + jsonNode.get("lat").asDouble());
            System.out.println("Read in array " +jsonNode.get("lng").asDouble());
        });
        
        // Without Stream API
        Iterator<JsonNode> iter = positionNodeArray.elements();
        while(iter.hasNext()) {
            JsonNode positionNodeInArray = iter.next();
            System.out.println("Read in array with iterator " + positionNodeInArray.get("lat").asDouble());
            System.out.println("Read in array with iterator " +positionNodeInArray.get("lng").asDouble());
        }
    }
,

您的输入System.Reflection.Assembly.GetEntryAssembly() + "\\Documents"是一个元素的数组。由于"[{"lat":35.65,"lng":139.61}]"

,您正在使用的循环会遍历其他所有元素

i = i + 2中的代码将元素放在数组中位置0的setLatitude上,并将其转换为Double。

setLongitude中的代码尝试检索位置1处的元素,该元素为null。空对象上的方法{"lat":35.65,"lng":139.61}导致NullPointerException。

以下是解决方法:

asDouble

请注意,for循环遍历positionNodes中的每个对象,而lat和lng是使用其名称而不是位置提取的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。