Java REST API从字符串返回JSON

mspsb9vt  于 2023-02-14  发布在  Java
关注(0)|答案(1)|浏览(136)

我有一个JSON存储在我的数据库中,我想返回jax-rs get服务中的那个json,而不使用POJO。有什么方法可以做到这一点吗?我尝试只在String中设置它,但结果被转义。我也尝试返回一个JSONObject,但我得到了"org.codehaus. jackson.map. JsonMappingException:没有为类org.json.JSONObject "找到序列化器,所以我想我不能使用那个对象类型。最后我使用了一个JSONNode,它返回了如下的数据:

{
      "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
    }

密码。

@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
     }
}

有什么办法吗?谢谢。
jax-rs,网络逻辑12.1.3

zzlelutf

zzlelutf1#

我有一个类似的需求,但我所做的只是将它从Gson序列化到实体,以便在内部处理它,当打印或保存它时,只需将它序列化回Gson,逻辑如下(* 顺便说一下,我在两种方式中都使用了Gson *):

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

这里的实体:

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

获取JSON并将其转换为实体的逻辑非常简单:

Gson gson = new Gson();
Entity repoSequence = gson.fromJson(jsonString, Entity.class);

相关问题