0

I have a piece of code.

I need to map employeeRows to List<Map<String, Object>> using ObjectMapper to pass it as an argument in createResponse method.

Could someone help me with this?

Publisher<employee> employeeRows = employeeService.list();

// Create response with our results
return createResponse(request, employeeRows, pivotValues);
Lii
  • 11,553
  • 8
  • 64
  • 88
Anamika
  • 75
  • 1
  • 8
  • Can you add more detailes , what is employee Rows and what is employee model ? maybe add an example ? – George Feb 22 '22 at 11:43

2 Answers2

0

I think that this question is similar to: Map JSON To List<Map<<String, Object>> As the answer states you can use TypeReference to achieve mapping into List<Map<String,Object>>

0

You would need to provide more details in your question, but I would try to make an reasonable assumptions and provide you with my best guess answer. First of all, why is in your code
Publisher<employee> employeeRows = employeeService.list();
you invoke method called list() but it returns an instance of a class Publisher<employee> and not a list. Also if you try to serialize any instance of a class that is not a list into Json you will get a Json object (equivalent of a Map<String, Object> and not List<Map<String, Object>>). So, if you want to get a JSON list (equivalent of List<Map<String, Object>>) you have to have a List<Employee>. To do so is a strait forward task. You can use ObjectMapper class for it. But also I wrote am Open-source library that has a class JsonUtils which is a simple wrapper over ObjectMapper class that may simplify this task for you. Assuming you have a List<Employee> your code would look like this:

try {
  String jsonListString = writeObjectToJsonString(myEmployeeList);
} catch(JsonProcessingException jpe) {
  ...
}

Here is a Javadoc for JsonUtils class. The library called MgntUtils and you can get it as maven artifact or on Github (including source code and Javadoc)

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
  • It is not a good idea to catch `Exception`. It is very easy to get an unexpected exception from a bug, then catch it and hide a problem. It is better to only catch a more specific expected exceptions. – Lii Feb 22 '22 at 12:42
  • @Lii This is just an example to demonstrate a code. The method `writeObjectToJsonString` happens to throw `com.fasterxml.jackson.core.JsonProcessingException`. So for proper example I placed try - catch block there. But a user may catch any specific exception or not to catch it at all and have the method propogate it up. It is just an example – Michael Gantman Feb 22 '22 at 13:04
  • 1
    Catching `Exception` is such a common newbie mistake, so it is good to steer them away from that habit by never doing that in any examples! Just make up `SomeException` or similar instead! – Lii Feb 22 '22 at 13:16
  • @Lii, Pont taken. Answer modified – Michael Gantman Feb 22 '22 at 13:45