Search code examples
javajsonspring-bootjooq

How to convert JSON (org.jooq.JSON) to Java Object (POJO)


I have tried lot of ways to find to convert JSON object (org.jooq) to java object (pojo). I am working on spring-boot application using jOOQ to talk with the database.

Actually I have a employee_details table in database shown in below:

enter image description here

In the above table has employee details, In that table emp_address column type is JSON datatype

Now I want to retrieve the one employee_details from table where id=X and I tried to store the details in below java object class (POJO).

EmployeeDetails class:

@AllArgsConstructor
@NoArgsConstructor
@Data
public class EmployeeDetails {
    private int              id;
    private String           emp_name;
    private String           emp_email;
    private String           emp_mobile;
    private EmployeeAddress  emp_address;
}

EmployeeAddress class:

@AllArgsConstructor
@NoArgsConstructor
@Data
public class EmployeeAddress {

    private String hNo;
    private String city;
    private String pincode;
}

But when I try to retrieve the details from table I got store the emp_address(which is json datatype in table) in Json(org.jooq) as shown in below class.

EmployeeDetailsJSONJooQ class:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.jooq.JSON;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class EmployeeDetailsJSONJooQ {
    private  int        id;
    private  String     emp_name;
    private  String     emp_email;
    private  String     emp_mobile;
    private  JSON       emp_address;
}

Here I want to retrieve the employee details in either EmployeeDetails object or help me to convert the EmployeeDetails object to EmployeeDetailsJSONJooQ object or how to map these objects using Mapstruct. Please help me out


Solution

  • If you're not too opinionated on how the JSON should be mapped to your POJOs, it should suffice to place either Gson or Jackson on your classpath, and jOOQ will pick that up and map JSON to your POJOs automatically, see this section of the manual about the ConverterProvider.

    E.g. this should work out of the box:

    List<EmployeeDetails> list =
    ctx.selectFrom(EMPLOYEE_DETAILS)
       .fetchInto(EmployeeDetails.class);