I tried this:
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.apache.commons.lang.Validate;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.print.attribute.standard.Media;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.io.Serializable;
public static class MyJSON implements Serializable {
private final String name = "myname";
// **Why don't I get this field serialized in the response?**
private final JSONObject jsonObject = new JSONObject();
public MyJSON() {
try {
jsonObject.put("mykey", "myvalue");
} catch (JSONException e) {
e.printStackTrace();
}
}
public String getName() { return name; }
public JSONObject getJsonObject() { return jsonObject; }
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get all entities", notes = "get all entities", response = Response.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK status"),
public Response getList() {
return Response.ok(new MyJSON(), MediaType.APPLICATION_JSON).build();
}
the response I get:
{
"name": "myname"
}
as you see I get only the name field of MyJSON without the jsonObject field.
any ideas how can I get the jsonObject fields also serialized?
UPDATE:
after reading Thomas comment I tried using a map:
public static class MyJSON implements Serializable {
private final String name = "myname";
private final Map somefield = new HashMap();
public String getName() { return name; }
public Map getSomefield() { return somefield; }
public void addOther(String key, String value) {
somefield.put(key, value);
}
}
MyJSON myJSON = new MyJSON();
myJSON.addOther("mhykey", "myvalue");
return Response.ok(myJSON, MediaType.APPLICATION_JSON).build();
Now I get again:
{
"name": "myname" // where is the other field? (the map)
}
I wonder again why doesn't it serializes it? please note I can't use specific objects because the json can vary at one scenario certain fields at another scenario other fields, I can't create a new class for each such case.
Map<String, Object>instead ofJSONObject? Since the pojo is serialized to json the mapper might have problems when encounteringJSONObjects directly. Besides that it might be better to use specific objects anyways, i.e. instead of a map you could provide a nested pojo that has themykeyfield.{ "name": "value", "mykey": "myvalue" }