Reputation: 5029
I am using Jersey to implement REST apis. Other than all the endpoints, I wanted to create a about page that lists all the endpoints and their usages.
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response displayInfo() {
JSONObject json = createInfoJson();
return Response.ok(json).build();
}
/////////////////////////////////////////
public static JSONObject createInfoJson() {
JSONArray ja = new JSONArray();
JSONObject jo1 = new JSONObject();
jo1.put("baseurl", "/tests/");
jo1.put("description", "Basic Information page");
jo1.put("example", "/tests/");
ja.put(jo1);
JSONObject jo2 = new JSONObject();
jo2.put("baseurl", "/tests/sendmsg");
jo2.put("description", "Run Kafka Test");
jo2.put("example", "/tests/sendmsg?count=100");
ja.put(jo2);
ja.put(jo2);
JSONObject json = new JSONObject();
json.put("name", "Kafka Messaging Test");
json.put("endpoints", ja);
return json;
}
When I hit the about page in a browser, I got the following error:
No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer
(to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
What is the correct way to return a JSONObject object from Jersey?
Upvotes: 1
Views: 530
Reputation: 1664
You're trying to serialize JSONObject to JSON, it doesn't work this way (error explains why). But you have at least two options:
Serialize json
to String:
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response displayInfo() {
JSONObject json = createInfoJson();
return Response.ok(json.toString()).build();
}
Create Model/POJO for your response and use it instead JSONObject.
Upvotes: 3