【问题标题】:Java REST API return JSON from stringJava REST API 从字符串返回 JSON
【发布时间】:2015-09-22 20:25:27
【问题描述】:

我的数据库中存储了一个 JSON,我想返回该 json,因为它在 jax-rs 获取服务中,而不使用 POJO。有没有办法做到这一点?我尝试将其设置为字符串,但结果被转义。我也尝试返回一个 JSONObject,但我得到了“org.codehaus.jackson.map.JsonMappingException: No serializer found for class 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,weblogic 12.1.3

【问题讨论】:

  • 可能的解决方案可能在这里 - stackoverflow.com/questions/13243037/…
  • 您使用的是哪个库?如果您使用内置的 HTTP 库,您将返回一个 InputStream,您可以将其复制到一个字符串中。
  • 哇,这是一种非常低效的指定类型的方法。
  • 我在这里没有看到其他相关的东西
  • 为了让 Jackson 反序列化 JSONObject,您需要注册 JSON.org Jackson 模块 (github.com/FasterXML/jackson-datatype-json-org)。代码如下所示 - ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JsonOrgModule());

标签: java json


【解决方案1】:

我也有类似的需求,但我所做的只是将它从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);

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 2020-11-10
    • 2010-12-04
    相关资源
    最近更新 更多