Reputation: 2760
Let us take the following JSON
response which I want to return from my REST service
,
{
"id" : 123,
"name" : "ABC",
}
For the above JSON
response, I can create a POJO
class like,
public class Student{
private long id;
private String name;
//getters and setters
}
So, I can write a GET service
to return the Student
object which will be then transformed as JSON
.
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response get(){
Student student = new Student();
student.setId(123);
student.setName("ABC");
return Response.ok(student).build();
}
It works fine. Now I want to introduce optional parameters to my JSON
response as follows,
{
"id" : 123,
"name" : "ABC",
"params" : {"param1":"xxx","param2":342}
}
Here the params
in the JSON
response is an Object
type and the attributes of that object are not fixed. It will vary for every request like sometime it can have 3 attributes and sometime it will have none. I don't know how to create my POJO
class for this requirement. Can anybody suggest me a way how to do it?
Upvotes: 1
Views: 821
Reputation: 847
Unless you don't need anything special, you should design it as like:
public class Student{
private long id;
private String name;
//getters and setters
private Map<String, String> parameters = new HashMap<>();
public void add(String key, String value) {
parameters.put(key, value);
}
public void addAll(Map<String, String> map) {
parameters.putAll(map);
}
}
If you need type safety then the design is little bit complicated a consider using something like:
class StudentParameters {
long param1;
String param2;
}
and Student:
public class Student{
private long id;
private String name;
//getters and setters
private StudentParameters studentParameters;
public setStudentParameters(final StudentParameters studentParameters) {
this.studentParameters = studentParameters;
}
}
Do not create complex hierarchies e.g Map<List<List>, List<List>>
it will complicate whole structure.
Upvotes: 2