REST Web服务JSON格式

时间:2014-05-03 10:00:42

标签: java json web-services rest

我正在尝试创建一个返回用户详细信息的REST Web服务。

这是我的代码:

//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;
    }

这会生成以下JSON:

{
    "email": "adrian.olar@email.ro",
    "fname": "Adrian",
    "lname": "Olar",
    "touristId": 1
}

我需要的是:

    {"tourist":{
            "email": "adrian.olar@email.ro",
            "fname": "Adrian",
            "lname": "Olar",
            "touristId": 1
        }
    }

我需要在代码中添加什么来产生这个?

1 个答案:

答案 0 :(得分:1)

如果确实希望将Tourist包装到另一个对象中,则可以执行此操作。

Tourist.java

package entities;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Tourist {

    int touristId;
    String email;
    String fname;
    String lname;

TouristWrapper.java

package entities;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class TouristWrapper {

    Tourist tourist;

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;
    }
}

我简化了您的用例,但您明白了这一点:不返回Tourist,而是TouristWrapper。返回的JSON是:

{
    "tourist": {
        "email": "foo@example.com",
        "fname": "John",
        "lname": "Doe",
        "touristId": 1
    }
}