Can we create an object in Java with out class like in js or python with random key and values

32
June 26, 2022, at 5:10 PM

Like in other programing languages - python or JS, when we create a rest api specifically post for the request body we attract some JSON Object

EX:

url: .../employee (Post)

request body: {option: {filter: "suman"}}

In Python or JS we can just do request_body.option.filter and get the data

How can I achieve the same with Java ? Do I need need to create a class for the reqeust_body and for option and make an instance object request_body

Answer 1

This depends with other framework elements you use in your application. For example if you bring Spring into the scene, you would be looking to use in built features like dependency injection and support for hibernate (JPA implementation), which depends on the concept of entities that are POJOs with extra annotations. So yes you would need to define entity classes and DTOs for those.

Answer 2

I was able to parse the request body with JSONObject like below

@PostMapping("/customers")
    public List<Customer> getCustomerById(@RequestBody Map<String, Object> req) {
        // {option: {filter: "alf"}}
        JSONObject json = new JSONObject(req);
        System.out.println(json.toString(4));
        System.out.println(json.getJSONObject("option").get("filter"));
        -----------------------
        -----------------------
        -----------------------

}

Output

Rent Charter Buses Company
READ ALSO
Jenkins pipeline library build using Java instead of Groovy

Jenkins pipeline library build using Java instead of Groovy

I would like to write my company Jenkins Pipeline Library using Java not Groovy, as groovy is slower than JavaI tried to find examples of such Java Jenkins library source code, but I found only Groovy

54
How to insert Repeated Record in BigQuery using java client library

How to insert Repeated Record in BigQuery using java client library

I am very new to BigQuery and need help to resolve below mentioned query

38
How to execute methods after the OnCreateView?

How to execute methods after the OnCreateView?

I'm working on an Android app in Java where a class is called and measurements are made in the OnCreateView methodHowever I have to automate the sending of his measurements once finished

57