Akhil Soni
Akhil Soni

Reputation: 73

Is there any real light 4j examples for mapping json request to Java POJO objects?

It happens to me that I am bound to use light 4j . I couldn't find a simple example of a simple CRUD service in entire source code base of light 4j.

All there examples simply return dummy response in their handler.

None of them have actually injected a service and perform any logic .

Q1) Is anyone aware of any documentation or sample source code of light 4j which is complete in terms of CRUD operation including how to inject services with multiple implementation ? PS : There documentation just display how to get ALL the implementations of a Service and not a SINGLE implementation out of many.

Q2) The actual question : How to convert a very simple JSON Request body to a JAVA POJO object .

The worst of all possibility I found out is this .

Map<String, Object> bodyMap = (Map<String, Object>) exchange
                .getAttachment(BodyHandler.REQUEST_BODY);
        AccontRegisterRequest request = new AccontRegisterRequest();
        request.setDob(LocalDate.parse((String) bodyMap.get("dob")));
        request.setName((String) bodyMap.get("name"));
        request.setInitialDeposite(
                Float.parseFloat((String) bodyMap.get("initialDeposite")));

Request Payload

{
   "name" : "Some Name",
   "dob"   : "1999-02-02",
   "initialAmount" : 10000
 }

Please dont recommend of adding a key in this JSON like this :

{
   "somekey like body" : {
        ... and here goes by previous json
     }
}

Because this BodyHandler is UN-NECESSARILY reading the input stream and converts it into a linkedHasMap.

So I cannot simply read the request input stream in my logic and pass it to JACKSON mapper to create my POJO.

Please help me to get me rid of this .

Upvotes: 0

Views: 406

Answers (1)

Steve Hu
Steve Hu

Reputation: 388

Sorry I didn't find this question in my previous scan.

You can convert a map to POJO with Jackson and it is very fast as there is no need to parse the JSON.

Take a look at this example in light-oauth2

https://github.com/networknt/light-oauth2/blob/master/client/src/main/java/com/networknt/oauth/client/handler/Oauth2ClientPostHandler.java#L44

Upvotes: 0

Related Questions