当响应是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;
}
}
答案 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"}