[英]Receive the InputStream and get the values from json string in Jersey
How can I received JSON string from the InputStream
in Jersey, which was sent from HttpURlConenction
in android, and how can I get the values of it to store them into database table? 如何从Jersey的
InputStream
接收JSON字符串,该字符串是从android中的HttpURlConenction
发送的,如何获取它的值以将它们存储到数据库表中?
{
"latitude":93.86898451,
"longitude":30.66561387,
"time":"24.04.2015 11:11:05",
"route":4
}
Jersey receiver class: 球衣接收器类别:
@Path("data")
public class Receiver {
@POST
@Consumes({MediaType.APPLICATION_JSON, "text/json"})
public void storeDate() {
BufferedReader in
= new BufferedReader(new InputStreamReader(process.getInputStream()));
}
}
With Jersey you should be able to just declare class Data (with Jackson annotations to support deserialization from JSON): 使用Jersey,您应该可以只声明类Data(带有Jackson批注以支持从JSON反序列化):
public class Data {
private double latitude;
private double longitude;
private String time;
private int route;
@JsonCreator
public Data(@JsonProperty("latitude") double latitude,
@JsonProperty("longitude") double longitude,
@JsonProperty("time") String time,
@JsonProperty("route") int route) {
this.latitude = latitude;
this.longitude = longitude;
this.time = time;
this.route = route;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public String getTime() {
return time;
}
public int getRoute() {
return route;
}
}
and then define your endpoint as: 然后将端点定义为:
@Path("/data")
public class Receiver {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response storeData(Data data) {
// do something with data
return Response.status(201).build();
}
}
and it should just work. 它应该可以正常工作。
1) If you can modify the client code add this line in your HttpURLConnection connection 1)如果可以修改客户端代码,请在HttpURLConnection连接中添加此行
connection.setRequestProperty("Content-Type", "application/json");
This will convert the input to a POJO 这会将输入转换为POJO
2)If you cannot edit the client HttpUrlConnection the bring in the stream as 2)如果您无法编辑客户端HttpUrlConnection,则将流作为
@Consumes("{*/*}")
public Something (String request){
ObjectMapper mapper = new ObjectMapper();
Data data = mapper.readValue(request, Data.class);
return = getSomething(data);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.