1

I have a JSON stored in my database, I want to return that json as it is in a jax-rs get service, without using a POJO. Is there any way to do that? I tried just setting it in a String, but the result is escaped. I also tried returning a JSONObject, but I got "org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.json.JSONObject", so I guess I cant use that object type. Finally I used a JSONNode, and it returned my data like this:

{
      "nodeType": "OBJECT",
      "int": false,
      "object": true,
      "valueNode": false,
      "missingNode": false,
      "containerNode": true,
      "pojo": false,
      "number": false,
      "integralNumber": false,
      "floatingPointNumber": false,
      "short": false,
      "long": false,
      "double": false,
      "bigDecimal": false,
      "bigInteger": false,
      "textual": false,
      "boolean": false,
      "binary": false,
      "null": false,
      "float": false,
      "array": false
    }

The code.

@GET
@Path("/campanas")
public Response obtenerCampanas(@HeaderParam("Authorization") String sessionId) {
    ResponseBase response = new ResponseBase();
    int requestStatus = 200;
    CampanaResponse campanaResponse = campanasFacade.obtenerCampanas();
    response.setData(campanaResponse);
    response.setRequestInfo(GlosaCodigoRequest.OPERACION_EXITOSA);
    return Response.status(requestStatus).entity(response).build();
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Campanas")
public class CampanaResponse implements Serializable {
    private static final long serialVersionUID = -7414170846816649055L;
    @XmlElement(name = "campanas", required = true)
    private List<Campana> campanas;
    @XmlElement(name = "fecha", required = true)
    private Date fecha;

    //getters.. setters

    public static class Campana {
        private String idCampana;
        private String nombre;
        private String urlBanner;
        private String global;
        private String numeroCuenta;
        private Date fechaDonaciones;
        private Date fechaInicio;
        private Date fechaFin;
        private JSONObject config;

        //getters..setters
     }
}

Is there any way to do that? Thanks.

jax-rs, weblogic 12.1.3

Ed_
  • 368
  • 1
  • 4
  • 22
  • 1
    Possible solution could be here - http://stackoverflow.com/questions/13243037/issue-with-i-o-no-serializer-found-for-class-org-json-jsonobject-and-no-properti – Ivan Ursul Sep 22 '15 at 20:27
  • Which libarary are you using? If you use the built in HTTP library you will get back an InputStream you can copy into a String. – Peter Lawrey Sep 22 '15 at 20:27
  • 4
    Wow, that's an impressibly inefficient way to specify the type. – Peter Lawrey Sep 22 '15 at 20:28
  • I dont see rest related thing here – Antoniossss Sep 22 '15 at 21:11
  • Sorry, now it is as it should in the beggining (hope you dont mind the spanish in the code) – Ed_ Sep 22 '15 at 21:24
  • 1
    In order to have Jackson deserialize a JSONObject you need to register the JSON.org Jackson Module (https://github.com/FasterXML/jackson-datatype-json-org). Code looks like this - ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JsonOrgModule()); – John McClean Sep 22 '15 at 21:42
  • https://stackoverflow.com/q/56754562/11695641 please help!! – Wade Jun 25 '19 at 13:02
  • Have you tried @Produces("application/json") on your service method and returning a String. That should have the desired effect. If not, please try and check. – Ironluca Jun 25 '19 at 13:56

1 Answers1

0

I had a similar requirement, but what I did was just to serialized it from the Gson to the entity to handle it internally, and when print it or save it, just serializes it back to GSON, the logic is something like this (by the way, I used Gson for both ways):

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.data.repository;
import com.data.Entity;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@Path("/rest")
public class RestService {    
    /*
    ... Other calls
    */
    private String toJson(Object entity) {
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss.SSS zzz")
                .setPrettyPrinting()
                .create();
        String result = gson.toJson(entity);
        return result.replace("\\\"", "");
    }

    @GET
    @Path("/{param1}/{param2}")
    @Produces({"application/xml", "application/json", "text/plain", "text/html"})
    public Response getEntity(@PathParam("param1") String param1, 
                              @PathParam("param2") String param2) {
        Entity entity = repository.getEntity(param1, param2);
        if (entity == null) {
            return Response
                    .status(Response.Status.NOT_FOUND)
                    .entity(
                    String.format(
                    "param1 %s does not have a valid record for param2 %s", 
                    param1, param2))
                    .build();
        }
        return Response.ok(this.toJson(entity)).build();
    }
}

And here the entity:

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;

import java.util.Date;

public class Entity {

    @SerializedName("Field1")
    private String field1;

    @SerializedName("Field2")
    private int field2;

    @SerializedName("Field3")
    private int field3;

    @SerializedName("Field4")
    private Date field4;

    public Entity() {
    }

    /*
    ... 
    ... Gets and Sets
    ...
    */

    @Override
    public String toString() {
        Gson gson = new Gson();
        String json = gson.toJson(this, Entity.class);
        return json;
    }
}

And the logic to get the json and translate it to the entity is as simple as this:

Gson gson = new Gson();
Entity repoSequence = gson.fromJson(jsonString, Entity.class);
halfer
  • 19,824
  • 17
  • 99
  • 186
Marco Vargas
  • 1,232
  • 13
  • 31