Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: How to write lambda stream to work with JsonArray?

I'm very new to Java 8 lambdas and stuff... I want to write a lambda function that takes a JSONArray, goes over its JSONObjects and creates a list of values of certain field.

For example, a function that takes the JSONArray: [{name: "John"}, {name: "David"}] and returns a list of ["John", "David"].

I wrote the following code:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class Main {
    public static void main(String[] args) {
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(new JSONObject().put("name", "John"));
        jsonArray.add(new JSONObject().put("name", "David"));
        List list = (List) jsonArray.stream().map(json -> json.toString()).collect(Collectors.toList());
        System.out.println(list);
    }
}

However, I get an error:

Exception in thread "main" java.lang.NullPointerException

DO you know how to resolve it?

like image 518
CrazySynthax Avatar asked Jun 16 '17 18:06

CrazySynthax


People also ask

How do I iterate through JSONArray?

1) Create a Maven project and add json dependency in POM. xml file. 2) Create a string of JSON data which we convert into JSON object to manipulate its data. 3) After that, we get the JSON Array from the JSON Object using getJSONArray() method and store it into a variable of type JSONArray.

How does Stream API works internally in Java 8?

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.

How do I read JSONArray?

String value = (String) jsonObject. get("key_name"); Just like other element retrieve the json array using the get() method into the JSONArray object.

How do I create a JSONArray?

Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.


1 Answers

Try with IntStream.

List<String> jsonObject = IntStream
       .range(0,jsonArray.size())
       .mapToObj(i -> jsonArray.getJSONObject(i))
       .collect(Collectors.toList());
like image 137
Adrian Avatar answered Sep 27 '22 20:09

Adrian