【发布时间】:2014-11-04 18:59:53
【问题描述】:
我正在尝试创建一个 REST 服务,它将以 JSON 作为POST 方法的输入。然后服务会将其存储在数据库中并返回响应。我在question 中尝试创建了一个名为 jsonFormat 的类。这个类的代码 -
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Aj
* This class forms the format of the JSON request which will be recieved from the App
*/
@XmlRootElement
public class JsonFormat {
public double longitude;
public double latitude;
public long IMSI;
public JsonFormat(){}
public JsonFormat(double longitude,double latitude, long IMSI){
this.longitude = longitude;
this.latitude = latitude;
this.IMSI = IMSI;
}
}
但是,我仍然收到 不支持的媒体类型 HTTP 415 响应。
我正在使用 Chrome 的 POSTMAN 插件进行测试。
这是我的服务实现代码 -
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.POST;
import org.json.simple.JSONObject;
/**
* REST Web Service
*
* @author Aj
*/
@Path("Offers")
public class OffersResource {
@Context
private UriInfo context;
/**
* Creates a new instance of OffersResource
*/
public OffersResource() {
}
@Path("/storeMovement")
@POST
@Consumes("application/json")
@Produces("application/json")
public String storeTrace(JsonFormat jsonObj) {
JSONObject response = new JSONObject();
String ret = "";
try {
RecordMovement re = new RecordMovement(jsonObj.longitude, jsonObj.latitude, jsonObj.IMSI);
ret = re.Store();
// Clear object
re = null;
System.gc();
response.put("status", ret);
} catch (Exception e) {
response.put("status", "fail");
}
return response.toJSONString();
}
/**
* PUT method for updating or creating an instance of OffersResource
*
* @param content representation for the resource
* @return an HTTP response with content of the updated or created resource.
*/
@PUT
@Consumes("application/json")
public void putJson(String content) {
}
}
我传递的 JSON 是 -
{"longitude": "77.681307",
"latitude": "12.8250278",
"IMSI": "404490585029957"}
在提交请求时,我确保将类型设置为 POST 并且 URL 正确 (http://localhost:8080/Offers/webresources/Offers/storeMovement)。
有人可以看看并建议我做错了什么吗?我浏览了多个站点,其中错误主要是由于未设置内容类型,但这里显然不是这种情况!
【问题讨论】:
-
请注意,您正在将@XmlRootElement 用于处理json 的类。但是您的 JsonFormat 类可能需要像 Jackson 这样的解析器。
-
@AndreasGnyp 你的意思是我应该在 JSONFormat 类的构造函数中使用 Jackson 的 ObjectMapper 吗?
-
是的。我将它与方法一起使用,但它也可以与构造函数一起使用。您可能还需要自己编写映射器。
标签: java json web-services rest