Java 8: How to write a 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, iterates over the JsonObjects and creates a list of the values โ€‹โ€‹of a specific field.

For example, a function that takes a JsonArray: [{name: "John"}, {name: "David"}] and returns a list ["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 am getting the error:

Exception on thread "main" java.lang.NullPointerException

Do you know how to solve it?

+4


source to share


3 answers


JSONArray is subclass java.util.ArrayList

and JSONObject is subclass java.util.HashMap

.

Hence, it new JSONObject().put("name", "John")

returns the previous value associated with key ( null

), not the instance JSONObject

. The result is null

added to JSONArray

.

This, on the other hand, works:

    JSONArray jsonArray = new JSONArray();
    JSONObject j1 = new JSONObject();
    j1.put ("name", "John");
    JSONObject j2 = new JSONObject();
    j2.put ("name", "David");
    jsonArray.add(j1);
    jsonArray.add(j2);
    Stream<String> ss = jsonArray.stream().map (json->json.toString ());
    List<String> list = ss.collect (Collectors.toList ());
    System.out.println(list);

      



For some reason, I had to split the stream pipeline into two steps, because otherwise the compiler won't recognize what it .collect (Collectors.toList())

returns List

.

Output:

[{"name":"John"}, {"name":"David"}]

      

+4


source


Try with IntStream



> List<String> jsonObject = IntStream
>      .range(0,jsonArray.length())
>      .mapToObj(i -> jsonArray.getJSONObject(i))
>      .collect(Collectors.toList());

      

0


source


Go to the list first, then you can use the stream in the usual way

private class MyClass{
    public MyClass(JSONObject json) {
    }    
}

private List<MyClass> jsonArrayToMyClassList(JSONArray jsonArray){

    List<JSONObject> jsonList = (List<JSONObject>) jsonArray
            .stream()
            .map(JSONObject.class::cast)
            .collect(Collectors.toList());

    return jsonList
            .stream()
            .map(MyClass::new)
            .collect(Collectors.toList());
}

      

-1


source







All Articles