I'm very new to Java 8 lambdas and stuff... I want to write a lambda function that takes a JSONArray
, goes over its JSONObject
s 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?
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.
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.
String value = (String) jsonObject. get("key_name"); Just like other element retrieve the json array using the get() method into the JSONArray object.
Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.
Try with IntStream.
List<String> jsonObject = IntStream
.range(0,jsonArray.size())
.mapToObj(i -> jsonArray.getJSONObject(i))
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With