How to Convert List to JSON in Java

How to convert List to Json in Java

Use GSON library for that. Here is the sample code

List<String> foo = new ArrayList<String>();
foo.add("A");
foo.add("B");
foo.add("C");

String json = new Gson().toJson(foo );

Here is the maven dependency for Gson

<dependencies>
<!-- Gson: Java to Json conversion -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.2</version>
<scope>compile</scope>
</dependency>
</dependencies>

Or you can directly download jar from here and put it in your class path

http://code.google.com/p/google-gson/downloads/detail?name=gson-1.0.jar&can=4&q=

To send Json to client you can use spring or in simple servlet add this code

response.getWriter().write(json);

How to convert list data into json in java

public static List<Product> getCartList() {

JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();

List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", "1");
formDetailsJson.put("name", "name1");
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format

return cartList;

}

you can get the data in the following form

{
"forms": [
{ "id": "1", "name": "name1" },
{ "id": "2", "name": "name2" }
]
}

Convert List to JsonObject in Java using json simple

Got the answer -

First converted the List to Map and then to Json -

public Map<String, String> test() {

Map<String, String> result = items.stream().collect(Collectors.toMap(Item::getValue, Item::getType)); //Converts List items to Map

System.out.println("Result : " + result);

JSONObject json = new JSONObject(result); //Converts MAP to JsonObject

System.out.println("JSON : " + json); //prints {"firstname":"abc","lastname":"pqr","id":"1"}
return result;
}

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 convert JSON string into List of Java object?

You are asking Jackson to parse a StudentList. Tell it to parse a List (of students) instead. Since List is generic you will typically use a TypeReference

List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});

How to convert an Array List of objects to Json

Play comes with play-json module which can do it. You might have to create a wrapping class to output the kunden root node:

public class Kunden {
private List<Kunde> kunden;
// getter and setter
}

Kunden root = new Kunden();
kunden.setKunden(...);

JsonNode rootNode = Json.toJson(root);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node);

Note that ObjectMapper is used to pretty print.

See the official Play Framework 2.6.X docs: Mapping Java objects to JSON.



Related Topics



Leave a reply



Submit