Access JSONObject field value in lambda expression Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Access JSONObject field value in lambda expression without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am pretty new to Java and I am quite found of fonctional programming. Here I am trying to write the most concise factory method to create a List<Manager> based on a JSONArray retrieved from an API. Here is a simplified version of what I have in mind

public List<Manager> getManagers(HashMap parameters) throws IOException, InterruptedException {
    JSONArray records = (JSONArray) api.getData("Manager", parameters).get("records");
    records.forEach(x -> new Manager(x.get("FirstName"),x.get("LastName")))

and how I would do it in python (I am highly biased)

manager_list = list(map(lambda x: Manager(x["FirstName"],x["LastName"]),records))

I am experiencing two issues.

  1. access JSONObject fields inside the lambda expression

Despite x being a JSONObject

records.forEach(x -> System.out.println(x.getClass()));
class org.json.JSONObject

x.get("FirstName") does not work in the lambda. Is it because .get() is an instance method or am I missing something else?

  1. easily append Managers to a list

This does not work

List managers = records.forEach(x -> new Manager(x.get("FirstName"),x.get("LastName")))

because forEach returns void. Does forEach have a cousin who could return any kind of Interable or Collection ?

Since I am new to java, I both interested in implementations for my actual problem and more general discussions on functional programming in modern java

Answer

Try the following:

public List<Manager> getManagers(HashMap parameters) throws IOException, InterruptedException {
        
    JSONArray records = (JSONArray) api.getData("Employee", parameters).get("records");

    List<Manager> managers = new ArrayList<>();
    records.forEach(jsonRecord -> {
        JSONObject record = (JSONObject) jsonRecord;
        managers.add(new Manager(record.getString("FirstName"), record.getString("LastName")));
    });

    return managers;
    }

You may have to cast each item into a JSONObject in order to access the properties.

We are here to answer your question about Access JSONObject field value in lambda expression - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji