如何从 JsonNode 中提取一个数组?

huangapple go评论67阅读模式
英文:

How to extract an array from a JsonNode?

问题

我有以下的输入:

如何从 JsonNode 中提取一个数组?

我想要提取纬度和经度。我尝试了下面的实现,但是在 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());  <--- 空指针异常 !!
            listOfEntrances.add(coordinateBE);
        }
        return listOfEntrances;
    }

我该如何修复上述实现?

英文:

I have the following input:

如何从 JsonNode 中提取一个数组?

I want to extract lat and long. I tried the following implementation, but I received null pointer exception for positionNode.get(i + 1).asDouble()

private List&lt;CoordinateBE&gt; getCoordinate(final JsonNode positionNode) {
        
        final List&lt;CoordinateBE&gt; listOfEntrances = new ArrayList&lt;&gt;();
        for (int i = 0; i &lt; positionNode.size(); i = i + 2) {
            final CoordinateBE coordinateBE = new CoordinateBE();
            coordinateBE.setLatitude(positionNode.get(i).asDouble());
            coordinateBE.setLongitude(positionNode.get(i + 1).asDouble());  &lt;--- Null Pointer Exception !!
            listOfEntrances.add(coordinateBE);
        }
        return listOfEntrances;
    }

How can I fix the above implementation ?

答案1

得分: 1

如果您正在使用com.fasterxml.jackson.databind.JsonNode,您可以通过字段名称获取预期的字段,而不是使用位置

  • 对于纬度使用 positionNode.get("lat").asDouble()
  • 对于经度使用 positionNode.get("lng").asDouble()

以下是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}" +
                "]");

        // 使用流式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());
        });
        
        // 不使用流式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());
        }
    }
英文:

If you are using com.fasterxml.jackson.databind.JsonNode, you can get the expected field by name, instead of using the position

  • positionNode.get("lat").asDouble() for the lat
  • positionNode.get("lng").asDouble() for the lng

Here an example in Java

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

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

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

答案2

得分: 0

你的输入&quot;[{&quot;lat&quot;:35.65, &quot;lng&quot;:139.61}]&quot; 是一个包含一个元素的数组。你正在使用的循环每次跳过一个元素,因为有 i = i + 2

在你的 setLatitude 方法内部,它获取了数组中位置 0 处的元素,即 {&quot;lat&quot;:35.65, &quot;lng&quot;:139.61},然后将其转换为 Double 类型。

在你的 setLongitude 方法内部,它试图获取位置 1 处的元素,但是该位置是空的。对空对象调用 asDouble 方法会导致空指针异常。

以下是修复方法:

private List<CoordinateBE> getCoordinate(final JsonNode positionNodes) {
    
    final List<CoordinateBE> listOfEntrances = new ArrayList<>();
    for (JsonNode positionNode : positionNodes) {
        final CoordinateBE coordinateBE = new CoordinateBE();
        coordinateBE.setLatitude(positionNode.get("lat").asDouble());
        coordinateBE.setLongitude(positionNode.get("lng").asDouble());
        listOfEntrances.add(coordinateBE);
    }
    return listOfEntrances;
}

请注意,这个 for 循环遍历了 positionNodes 中的每个对象,通过属性名而不是位置来提取纬度和经度。

英文:

Your input &quot;[{&quot;lat&quot;:35.65, &quot;lng&quot;:139.61}]&quot; is an array of one element. The loop you're using goes through every other element, because of i = i + 2

The code inside your setLatitude gets the element at position 0 in your array, which is {&quot;lat&quot;:35.65, &quot;lng&quot;:139.61}, and converts it into a Double.

The code inside your setLongitude tries to retrieve the element at position 1, which is null. The method asDouble on a null object causes the NullPointerException.

Here's how you can fix it:

    private List&lt;CoordinateBE&gt; getCoordinate(final JsonNode positionNodes) {
final List&lt;CoordinateBE&gt; listOfEntrances = new ArrayList&lt;&gt;();
for (JsonNode positionNode : positionNodes) {
final CoordinateBE coordinateBE = new CoordinateBE();
coordinateBE.setLatitude(positionNode.get(&quot;lat&quot;).asDouble());
coordinateBE.setLongitude(positionNode.get(&quot;lng&quot;).asDouble());
listOfEntrances.add(coordinateBE);
}
return listOfEntrances;
}

Notice that the for loop iterates through every object in positionNodes, and lat and lng are extracted using their name rather than position.

huangapple
  • 本文由 发表于 2020年10月26日 17:48:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/64534763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定