BAEL-6504: Convert Json Array to Java list (#14049)
This commit is contained in:
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.jsonarraytolist;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
|
||||
import entities.Product;
|
||||
|
||||
public class ConvertJsonArrayToList {
|
||||
|
||||
public List<Product> convertJsonArrayUsingGsonLibrary(String jsonArray) {
|
||||
Gson gson = new Gson();
|
||||
|
||||
Type listType = new TypeToken<List<Product>>() {}.getType();
|
||||
|
||||
List<Product> gsonList = gson.fromJson(jsonArray, listType);
|
||||
return gsonList;
|
||||
}
|
||||
|
||||
public List<Product> convertJsonArrayUsingJacksonLibrary(String jsonArray) throws JsonProcessingException {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
List<Product> typeReferenceList = objectMapper.readValue(jsonArray, new TypeReference<List<Product>>() {});
|
||||
return typeReferenceList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package entities;
|
||||
|
||||
public class Product {
|
||||
|
||||
private int id;
|
||||
private String name;
|
||||
private String description;
|
||||
|
||||
public Product() {}
|
||||
|
||||
public Product(int id, String name, String description) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user