'How to access nested Json Object Value into JPA Entity Class

I have a payload like this

{
    "eventId":"ep9_0579af51",
    "eventTime":"5/11/2022 5:50:58 PM",
    "eventType":"UpdateTransaction",
    "meta":{
        "userId":"vkp",
        "resourceType":"Transaction/DataDocs"
    }
}

I need to map this json fields into a single entity class .

@PostMapping(path = "/id", consumes = "application/json") 
public ResponseEntity<ImportTrans> import(@RequestBody ImportTrans importTrans) {
    return ResponseEntity.of(Optional.ofNullable(repository.save(importTrans););
}
@Table(name = "IMPORT_TRANS")
@Entity
public class ImportTrans implements Serializable {
    @Id
    private Long processId;// AutoGenerator
    private String eventId;
    private Date eventTime;
    private String eventType;

    private String userId; // I dont want create new class for meta . Is there any way i 
    //can access meta.userId in ImportTrans class.
    private String resourceType;
}

How can I access data from meta from ImportTrans without creating a separate class for it?



Solution 1:[1]

You should modify your request body before reaching the controller.

"You must consider the application performance factors on your own before implementation"

Option 1. Using RequestBodyAdvice.

Option 2. Using Spring HandlerInterceptor.

Option 3. Use AOP

Option 4. Using HTTP Filter.


The below solution only works if you are using a separate DTO class.

private Map<String, String> meta = new HashMap<>();

String userID = importTrans.getMeta().get("userId");

I hope the above pieces of information answered your question.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1