返回java对象时出现500错误,但返回String时却没有

时间:2019-03-04 17:08:37

标签: java jersey

当响应是java对象时,我一直收到500错误。但是,当我将对象转换为字符串时,就很好了。

  @GET
    @Path("/testJavaObj")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getJson() {
        SampleObj sampleObj = new SampleObj();

/* this converts the obj to String
String jsonObj = "";
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    try {
        jsonObj = ow.writeValueAsString(sampleObj);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
        return Response.ok(jsonObj).build();
/*

return Response.ok(sampleObj).build();
    }

公共类SampleObj实现可序列化{

            private String sampleUrl = "sampleUrl";

            public String getSampleUrl() {
                return sampleUrl;
            }

            public void setSampleUrl(String sampleUrl) {
                this.sampleUrl = sampleUrl;
            }

        }

1 个答案:

答案 0 :(得分:1)

我有下一个配置:

@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {

public static void main(String[] args) {
    new DemoApplication().configure(new SpringApplicationBuilder(DemoApplication.class)).run(args);
 }
}

然后我有Jersey配置:

@Component
public class JerseyConfig extends ResourceConfig {

public JerseyConfig() {
    register(Json.class);
 }
}

然后我有我的json类:

@Path("/testJavaObj")
@Produces(value = MediaType.APPLICATION_JSON)
public class Json {

@GET
public SampleObj getJson() {
    return new SampleObj();
 }
}

最后是SampleObj类:

public class SampleObj implements Serializable {
private String sampleUrl = "sampleUrl";

public String getSampleUrl() {
    return sampleUrl;
}

public void setSampleUrl(String sampleUrl) {
    this.sampleUrl = sampleUrl;
}

}

一切都对我有用。 响应为:

  {sampleUrl: "sampleUrl"}