简体   繁体   English

使用Jackson产生所需的JSON响应

[英]Using Jackson to produce desired JSON response

Could anyone tell me what am I doing wrong while printing the JSON using Jackson. 谁能告诉我在使用Jackson打印JSON时我在做什么错。 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 : 我在Employee类中定义了以下方法:

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循环,并将列表empStatus发送到OrmResponseToJsonString方法:

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

I am getting the following JSON response : 我收到以下JSON响应:

{
  "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 我的OrmResponseToJsonString方法在GenericOrmStatusView类中定义如下

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 : 我的printNameAndID方法在WebServiceUtils类中定义如下:

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 获得所需JSON输出的最简单方法是创建一个表示数据的对象模型,例如

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: 然后,您可以像这样创建JSON文本:

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 : 就像chrylis在评论中提到的那样

As a note, you can normally let Spring do this automatically and just return empList from your controller method. 需要注意的是,通常可以让Spring自动执行此操作,而只需从控制器方法return empList

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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