Search code examples
javajax-rsorg.jsonjavax.json

jax-rs consuming org.json.JSONObject respsonds with Exception


I am trying to build a rest api that should consume json/x-application data. Now I have looked into two libraries javax.json-api and org.json for handling the data.

Example JSON:

{
    "error": "false",
    "error_msg": "",
    "version": "1.13.10",
    "result": {
        "malware": {
            "finding1": {
                "file": "/path/to/filep",
                "malware": "{HEX}r2h.malware.blue.44"
            }
        }
    },
    "newest_version": "1.13.10"
}

If I now consume this with javax JsonObject, it will work and I can go on with my code. BUT, if i instead post this data and I use org.json.JSONObject I will receive response at the client:

Unrecognized field "error" (class org.json.JSONObject), not marked as ignorable

Tried to find responses on the web, but I didnt step over anything that explains this?

Regards and Thanks


Solution

  • Well,

    I do not really know if there is a solution for this. Eventually the REST architectural style does not support JSONObject (org.json.JSONObject). However, the workaround is pretty easy, just consume the json as a String (still you can declare HTTP Request to enforce the type application/json).

    So this could look like the following:

    @Path("/myendpoint")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public String receiveRequest(String json) {
        JSONObject jo = new JSONObject(json);
    ...
    }