2014-05-03 291 views
0

我正在嘗試創建一個返回用戶詳細信息的REST Web服務。REST Web服務JSON格式

這裏是我的代碼:

//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": "[email protected]", 
    "fname": "Adrian", 
    "lname": "Olar", 
    "touristId": 1 
} 

我需要的是:

{"tourist":{ 
      "email": "[email protected]", 
      "fname": "Adrian", 
      "lname": "Olar", 
      "touristId": 1 
     } 
    } 

我需要什麼添加到我的代碼生產這個?

+0

什麼語言? Java的? –

+0

是的,Java語言 –

+0

這不是一個有效的JSON,所以你不能違反規範。你確定這正是你想要的嗎? –

回答

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, "[email protected]", "John", "Doe"); 
     TouristWrapper touristWrapper = new TouristWrapper(tourist); 
     return touristWrapper; 
    } 
} 

我已經簡化了您的用例,但你明白了一點:沒有返回TouristTouristWrapper。返回的JSON是這樣的:

{ 
    "tourist": { 
     "email": "[email protected]", 
     "fname": "John", 
     "lname": "Doe", 
     "touristId": 1 
    } 
} 
+0

謝謝,這就是我一直在尋找的,我會嘗試這個 –

+0

很高興我能幫上忙。 –