简体   繁体   中英

Java REST API return JSON from string

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM