Spring Boot - Json Object Array to Java Array

Spring Boot - JSON Object Array to Java Array

You should probably create a Java class which represents the input JSON and use it in the method newPost(.....). For example:-

public class UserPostInfo {

private int userId;
private String postBody;
private String postTitle;
private Date created;
private List<String> tagList;
}

Also, include the getter/setter methods in this class.
If you want to modify the behavior of JSON parsing, you can use Annotations to change field names, include only non-null values, and stuff like this.

Convert list of Objects to JSON Array in java - Spring Boot api testing

It seems to me that the issue is that you are trying to pass something like the following JSON to the content:

[
{
"compania1_list": "Compania1 list",
"name1": "name1",
"s": "---",
"s1": "---",
"o": null,
"o1": null
},
{
"compania1_list": "Compania2 list",
"name1": "name2",
"s": "---",
"s1": "---",
"o": null,
"o1": null
}
]

This is a JSON Array with 2 JSON Objects and not a JSON Object with a JSON Array with 2 JSON Objects. My guess is that MockHttpServletRequestBuilder.content() method is not expecting JSON like this.

With this being said, I would change your Controller to accept an Object and not a Collection as follows:

@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/lista")
public Map<String, Object> createCompanias(@RequestBody CompaniasCreationRequest companiasCreationRequest) {
return companiaService.postListCompanias(companiasCreationRequest.getCompanias());
}

Being CompaniasCreationRequest as follows:

public class CompaniasCreationRequest {
private List<Compania> companias;

public CompaniasCreationRequest(List<Compania> companias) {
this.companias = companias;
}

public List<Compania> getCompanias() {
return companias;
}

public void setCompanias(List<Compania> companias) {
this.companias = companias;
}
}

In your test this would mean the following changes:

@Test
void successSavePostCompaniaLista() throws Exception {
Compania c1 = new Compania("Compania1 list",
"name1",
"---",
"---",
null,
null);
Compania c2 = new Compania("Compania2 list",
"name2",
"---",
"---",
null,
null);

CompaniasCreationRequest companiasCreationRequest = new CompaniasCreationRequest(List.of(c1,c2));

when(companiaRepository.save(any(Compania.class))).then(returnsFirstArg());

this.mockMvc.perform(
post("/companias/lista")
.header("authorization", "Bearer " + token)
.content(asJsonString(companiasCreationRequest))
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isCreated())
.andExpect(jsonPath("$.result[0].success[0]").isNotEmpty())
.andExpect(jsonPath("$.result[0].success[0].name").value(c1.getName()))
.andExpect(jsonPath("$.result[0].success[1].name").value(c2.getName()));
}

Now your request body will look like the following (which is a somewhat more standard JSON format):

{
"companias": [
{
"compania1_list": "Compania1 list",
"name1": "name1",
"s": "---",
"s1": "---",
"o": null,
"o1": null
},
{
"compania1_list": "Compania2 list",
"name1": "name2",
"s": "---",
"s1": "---",
"o": null,
"o1": null
}
]
}

How to create a json array with multiple objects java spring boot

String.valueOf(gameService.convertLikesToJsonArray(averageLikesPerGame)); 

You are making this a single value in the json, instead of it being actual json. That's why it's all escaped in your JSON output. You also haven't shown your pretty print method, so can't comment on the output of that. Try

    //Use object instead of String as you want nested objects in output
Map<String, Object> report = new HashMap<>();

String highestRankedGame = gameService.findHighestRatedGame();
String userWithMostComments = gameService.findUserWithMostComments();
Map<String,String> averageLikesPerGame = gameService.findAverageLikesPerGame();

report.put("highest_rated_game",highestRankedGame);
report.put("user_with_most_comments", userWithMostComments);
//Add averageLikesPerGame directly to report without modifying
report.put("average_likes_per_game",averageLikesPerGame.entrySet());

String jsonReport = gameService.convertReportToJson(report);

return jsonReport;

And

public String convertReportToJson(Map<String, Object> report) {

ObjectMapper mapper = new ObjectMapper();
String jsonArray = null;
try {
//Don't need Gson, can use writerWithDefaultPrettyPrinter with Jackson which
//You are already using
jsonArray = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(report);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return jsonArray;
}

If you want mapped values in the array with labels then you could do something like this

    List<Map<String,String>> labelledAvgLikesPerGame =
averageLikesPerGame.entrySet().stream()
.map( entry ->
//Needs java 9+ for ofEntries
//You'll need to make new HashMap,put + return
// for java 8
Map.ofEntries(
Map.entry("title", entry.getKey()),
Map.entry("average_likes", entry.getValue())
)).collect(Collectors.toList());

report.put("highest_rated_game",highestRankedGame);
report.put("user_with_most_comments", userWithMostComments);
report.put("average_likes_per_game",labelledAvgLikesPerGame);

Java Spring POST with array and object JSON data problem

Create a class that contains the alertKeeperDTOs-List and the deviceId as a wrapper. Then use it in your controller.

public class Device {
private List<AlertKeeperDTO> alertKeeperDTOs;
private Long deviceId;
//empty constructor
//getters and setters
}

public @ResponseBody String updateDeviceToKeeperList(@RequestBody Device device, HttpServletRequest request){


Related Topics



Leave a reply



Submit