Issue
I have a POJO.
@Data
@AllArgsConstructor
@Builder
public class Emp {
private String name;
private String position;
}
Suppose, we have created an object
Emp emp = new Emp("Manager", "Bob");
How can I convert it to a list and save it in a database in JSON format?
The data should be stored in the database in the format below:
{
list:[
{
position: Manager
name: Bob
}
]
}
Are there any ready solutions for that?
I converted an object into a list and then I called the .toString() method on it:
Collections.singletonList(emp);
But when I store it in the database, the next save goes to the database:
[Emp(position=Manager, name=Bob)]
But I need to store the record in a different way
Solution
How can I convert it to a list and save it in a database in JSON format?
The data should be stored in the database in the format below:
{ "list": [ { "position": "Manager" "name": "Bob" } ] }
Since the serialized JSON is required to have a property "list"
you can't simply serialize the List as is.
Instead, you can define a POJO wrapping this list.
That's how it might look like (I've made it generic in order to make it suitable for serializing any type of list):
@Data
@AllArgsConstructor
public static class ListWrapper<T> {
private List<T> list;
}
And that's how it can be serialized using Jackson's ObjectMapper
and ObjectWriter
:
List<Emp> emps = List.of(new Emp("Manager", "Bob"));
ListWrapper<Emp> listWrapper = new ListWrapper<>(emps);
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
String json = writer.writeValueAsString(listWrapper);
System.out.println(json);
Output:
{
"list" : [ {
"name" : "Manager",
"position" : "Bob"
} ]
}
Answered By - Alexander Ivanchenko
Answer Checked By - David Goodson (JavaFixing Volunteer)