2017-10-12 18 views
-1

가정 해 코드는 경로 매개 변수를 JAX-RS의 클래스로 변환하는 방법은 무엇입니까?

@Path("/app/{resource}") //Suppose resource comes as Apple or Mango. 
@Produces(value=MediaType.APPLICATION_JSON)  
public class AppResource { 

    @GET 
    public Response getResource(@PathParam("resource") String resource) { 
    // Here want to convert resource to Apple or Mango class so that I can create a List<Apple> or List<Mango>. 
    } 
} 

은 기본적으로 내가 {자원}에 온다 무엇이든 URI에 따라 목록 < 애플 > 또는 목록 < 망고 > 같은 일반적인 목록을 원 등이다. 당신은 당신의 코드가 명시 적 List<Apple>List<Mango> 목록을 갖고 싶어

+0

응답이'JSON' 이므로 거기에 유형이 없으므로'List '은 완벽하게 괜찮습니다. 필요한 경우 Apple의 항목이나 "망고"항목 만 목록에 넣는 것은 당신에게 달려 있습니다. – Andreas

답변

0

는, 당신은이 같은 코드 뭔가 작성해야합니다 :

@GET 
public Response getResource(@PathParam("resource") String resource) { 
    List<?> list; 
    switch (resource) { 
     case "apples": 
      list = getApples(); 
      break; 
     case "mangos": 
      list = getMangos(); 
      break; 
     default: 
      return Response.status(Status.NOT_FOUND).build(); 
    } 
    return Response.ok(list); 
} 

private List<Apple> getApples() { 
    List<Apple> appleList = new ArrayList<>(); 
    // add apples 
    return appleList; 
} 

private List<Mango> getMangos() { 
    List<Mango> mangoList = new ArrayList<>(); 
    // add mangos 
    return mangoList; 
} 

switch 문에 default 절은 보장을 그 /app/sailboats 같은에 대한 요청 404 "페이지를 찾을 수 없음"오류로 실패합니다.