I want to convert a JSON into a string field to save into database and again convert it back to JSON.
Ex. below is structure of JSON:
{
"students":[{
"name": "Albert",
"code":"GE",
"marks":[{"mark":"20"},{"mark":"40"}]},
{
"name": "Gert",
"code":"LE",
"marks":[{"mark":"26"}]},
{
"name": "John"
},
{
"name": "John Doe",
"code":"LP",
"marks":[{"mark":"40"}]}
]
}
I want to convert this into a String field, "storedInput", so that i can save it into database, ideally saving only the JSON data. I also want to convert it back to the JSON when I send it back to the user.
Below is the conversion strategy I used to convert it into delimited String.
"Albert-GE-20&40#Gert-LE-26#John-$-$#Johnah Doe-LP-40"
But I dont think its the best strategy as it gets extremely complicated to convert it back.
public String convertStudentList(List<Student> studentList) {
return studentList.stream().map(this::mapStudent).collect(Collectors.joining("#"));
}
public String checkData(String data) {
return Optional.ofNullable(data).isPresent() ? data : "$";
}
public String mapStudent(Student student) {
List<Marks> marks = student.getMarks();
if (marks != null) {
String mark = marks.stream().map(m -> m.getMark()).collect(Collectors.joining("&"));
return checkData(student.getName()) + "-" + checkData(student.getCode()) + "-" + mark;
} else {
return checkData(student.getName()) + "-" + checkData(student.getCode()) + "-" + "$";
}
}
Edit:
- I do not have access to make any changes to the table structure.
- I cannot simply store the entire JSON, ex. using Jackson Object Mapper, as there are space constraints, ideally i just want to store the value and convert it back.