Search code examples
javajsongsonjersey-2.0jackson-databind

Is there an automatic way to deserialize a json payload into a generic JsonObject without a POJO?


I have a rest API that consumes a simple JSON object, ie: { "prop": "value" }

@Consumes(MediaType.APPLICATION_JSON)
public Response apiName(@HeaderParam("field1") String field1, JsonElement payload){
   ...
}

I don't want to create a POJO for this or for other APIs that I will have later on. Instead, is there an automatic way for Jersey/Gson to deserialize the payload into a generic JsonElement/JsonObject?

I know I can do

new Gson().fromJson(payload,JsonObject.class)

at the beginning of each API but I'm sure that there is an automatic way to achieve this but I couldn't find any. All the docs/videos explaining this, they were using a POJO. If Jackson is better for this, do let me know. I'm not bounded to Gson.

I tried both JsonElement and JsonObject and for both I got: Cannot construct instance of com.google.gson.JsonElement (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information


Solution

  • I am not sure about Gson, but Jackson surely works.

    ...
    import com.fasterxml.jackson.databind.JsonNode;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RestController;
    ...
    
    
    @PostMapping("/create")
    public JsonNode create(@RequestBody JsonNode jsonNode){
        System.out.println(jsonNode.toString());
        return jsonNode;
    }