简体   繁体   中英

Using Jackson to produce desired JSON response

Could anyone tell me what am I doing wrong while printing the JSON using Jackson. Here's my controller code :

@RequestMapping(value="/get_employee_details", method=RequestMethod.GET)
    public String updateemployee
    (
            @RequestParam(value="emp_id", defaultValue="0") Integer emp_id,
            @RequestParam(value="name", defaultValue="") String name
    ) 
    {
        String responseJSON = null;
        boolean getStatus = true;       
        try {
            EmployeeDao employeeDao = (EmployeeDao)context.getBean("employeeDao");
            Employee employee = null;           
            List<Employee> empList = employeeDao.findByEmployeeId(emp_id);
            if ((empList != null) && (!empList.isEmpty())) {

                List<String> empStatus = new ArrayList<String>();
                for(Employee emp : empList){
                empStatus.add(emp.addJoinString());
                responseJSON = GenericOrmStatusView.OrmResponseToJsonString(true, 1,empStatus, true);
            }

            }                       
        }

        return responseJSON;
    }

I have the following method defined in my Employee class :

public String addJoinString() {
  return String.format("ID: %d",Name: %s," ,this.EmployeeId,this.name); 
}

Since I am running a for loop in the code here and sending the list empStatus to the OrmResponseToJsonString method :

for(Employee emp : empList){
                empStatus.add(emp.addJoinString());
                responseJSON = GenericOrmStatusView.OrmResponseToJsonString(true, 1,empStatus, true);

I am getting the following JSON response :

{
  "status" : "SUCCESS",
  "employeeStatus" : [ "ID: 81, Name: Jack", "ID: 83, Name: Anthony", "ID: 88, Name: Stephanie", "ID: 25, Name: Kelly", "ID: 02, Name: Jessica" ]
}

However, I would like to be it in the following format:

{
"status" : "SUCCESS",
"message": "  "
},
"employeeStatus":[{

"ID":81,
"Name":"Jack"

},
{

"ID":88,
"Name":"Anthony"

},

and so on and so forth ....


]

For Reference:

My OrmResponseToJsonString method is defined as follows inside GenericOrmStatusView class

public class GenericOrmStatusView extends Views 
{
    public static String OrmResponseToJsonString(boolean success, List<String> eStatus,boolean pretty)
    {
        PrintemployeeStatusIDAndStatus statusMsg = WebServiceUtils.printNameAndID(success, eStatus);        
        String genericOrmStatusJsonString = null;
        try {           
            ObjectMapper objectMapper = new ObjectMapper();                     
            objectMapper.configure(SerializationFeature.INDENT_OUTPUT, pretty);                                                             
            genericOrmStatusJsonString = objectMapper.writerWithView(Views.Normal.class).writeValueAsString(statusMsg);
            //genericOrmStatusJsonString = objectMapper.writerWithView(Views.Normal.class).writeValueAsString(eStatus);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return genericOrmStatusJsonString;
    }   
}

And my printNameAndID method is defined as follows inside WebServiceUtils class :

public class WebServiceUtils 
{

public static PrintNameAndID printNameAndID(boolean success,  List<String> eStatus)
    {
        PrintNameAndID statusMsgAndRegID = new PrintNameAndID();
        if (success) {          
            statusMsgAndRegID.setStatus("SUCCESS");
            statusMsgAndRegID.setemployeeStatus(eStatus);

        } else {            
            statusMsgAndRegID.setStatus("ERROR");
            //statusMsgAndRegID.setemployeeStatus("");
        }
        return statusMsgAndRegID;
    }   
}   

The easiest way to get desired JSON output, is to create an object model representing the data, eg

public class MyJSON {
    private MyStatus status;
    private List<EmployeeStatus> employeeStatus = new ArrayList<>();
    public MyJSON(String status, String message) {
        this.status = new MyStatus(status, message);
    }
    public void addEmployeeStatus(int id, String name) {
        this.employeeStatus.add(new EmployeeStatus(id, name));
    }
    public MyStatus getStatus() {
        return this.status;
    }
    public List<EmployeeStatus> getEmployeeStatus() {
        return this.employeeStatus;
    }
}
public class MyStatus {
    private String status;
    private String message;
    public MyStatus(String status, String message) {
        this.status = status;
        this.message = message;
    }
    public String getStatus() {
        return this.status;
    }
    public String getMessage() {
        return this.message;
    }
}
public class EmployeeStatus {
    private int id;
    private String name;
    public EmployeeStatus(int id, String name) {
        this.id = id;
        this.name = name;
    }
    @JsonProperty("ID")
    public int getId() {
        return this.id;
    }
    @JsonProperty("Name")
    public String getName() {
        return this.name;
    }
}

You can then create JSON text like this:

MyJSON myJSON = new MyJSON("SUCCESS", "  ");
myJSON.addEmployeeStatus(81, "Jack");
myJSON.addEmployeeStatus(88, "Anthony");

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
String json = objectMapper.writeValueAsString(myJSON);
System.out.println(json);

Output

{
  "status" : {
    "status" : "SUCCESS",
    "message" : "  "
  },
  "employeeStatus" : [ {
    "ID" : 81,
    "Name" : "Jack"
  }, {
    "ID" : 88,
    "Name" : "Anthony"
  } ]
}

As mentioned by chrylis in a comment :

As a note, you can normally let Spring do this automatically and just return empList from your controller method.

Which for the above code would mean something like this:

@GetMapping(path="/foo", produces="application/json")
public MyJSON foo() {
    MyJSON myJSON = new MyJSON("SUCCESS", "  ");
    myJSON.addEmployeeStatus(81, "Jack");
    myJSON.addEmployeeStatus(88, "Anthony");
    return myJSON;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM