[英]REST Web service JSON format
I am trying to create a REST web service that returns the details of a user. 我正在尝试创建一个返回用户详细信息的REST Web服务。
Here is my code: 这是我的代码:
//Actual web service methods implemented from here
@GET
@Path("login/{email}/{password}")
@Produces("application/json")
public Tourist loginUser(@PathParam("email") String email, @PathParam("password") String password) {
List<Tourist> tourists = super.findAll();
for (Tourist tourist : tourists) {
if (tourist.getEmail().equals(email) && tourist.getPassword().equals(password)) {
return tourist;
}
}
//if we got here the login failed
return null;
}
This produces the following JSON: 这将产生以下JSON:
{
"email": "adrian.olar@email.ro",
"fname": "Adrian",
"lname": "Olar",
"touristId": 1
}
What i need is: 我需要的是:
{"tourist":{
"email": "adrian.olar@email.ro",
"fname": "Adrian",
"lname": "Olar",
"touristId": 1
}
}
What would i need to add to my code to produce this? 我需要在代码中添加什么才能产生这种效果?
If you really want to wrap a Tourist
into another object, you can do this. 如果您真的想将
Tourist
包装到另一个对象中,则可以执行此操作。
Tourist.java
: Tourist.java
:
package entities;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Tourist {
int touristId;
String email;
String fname;
String lname;
TouristWrapper.java
: TouristWrapper.java
:
package entities;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class TouristWrapper {
Tourist tourist;
SOResource.java
: SOResource.java
:
package rest;
import entities.Tourist;
import entities.TouristWrapper;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
@Path("/so")
public class SOResource {
@GET
@Path("/tourists/{id}")
@Produces("application/json")
public TouristWrapper loginUser(@PathParam("id") int id) {
Tourist tourist = new Tourist(id, "foo@example.com", "John", "Doe");
TouristWrapper touristWrapper = new TouristWrapper(tourist);
return touristWrapper;
}
}
I have simplified your usecase but you get the point: No Tourist
is returned but a TouristWrapper
. 我简化了您的用例,但您明白了:没有返回任何
Tourist
,而是TouristWrapper
。 The JSON returned is this: 返回的JSON是这样的:
{
"tourist": {
"email": "foo@example.com",
"fname": "John",
"lname": "Doe",
"touristId": 1
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.