2012-01-14 6 views
2

この種のことは、URLの一部として配列またはオブジェクトのリストを取るRESTサービスを作成する方法を示すさまざまな例で説明しました。リストまたは配列をRESTeasyに渡すget

私の質問は、これをRESTeasyを使用して実装する方法ですか? 次のようなものが、これをどのように動作させると思いますか。

@GET 
    @Path("/stuff/") 
    @Produces("application/json") 
    public StuffResponse getStuffByThings(
      @QueryParam("things") List<Thing> things); 

答えて

3

StringConverterを作成し、ラッパーオブジェクトを使用します。ここでは、迅速かつ汚い例です。

public class QueryParamAsListTest { 
public static class Thing { 
    String value; 
    Thing(String value){ this.value = value; } 
} 

public static class ManyThings { 
    List<Thing> things = new ArrayList<Thing>(); 

    ManyThings(String values){ 
     for(String value : values.split(",")){ 
      things.add(new Thing(value)); 
     } 
    } 
} 

static class Converter implements StringConverter<ManyThings> { 

    public ManyThings fromString(String str) { 
     return new ManyThings(str); 
    } 

    public String toString(ManyThings value) { 
     //TODO: implement 
     return value.toString(); 
    } 

} 

@Path("/") 
public static class Service { 
    @GET 
    @Path("/stuff/") 
    public int getStuffByThings(
     @QueryParam("things") ManyThings things){ 

     return things.things.size(); 
    } 
} 



@Test 
public void test() throws Exception { 
    Dispatcher dispatcher = MockDispatcherFactory.createDispatcher(); 
    dispatcher.getProviderFactory().addStringConverter(new Converter()); 
    dispatcher.getRegistry().addSingletonResource(new Service()); 

    MockHttpRequest request = MockHttpRequest.get("/stuff?things=a,b,c"); 
    MockHttpResponse response = new MockHttpResponse(); 

    dispatcher.invoke(request, response); 

    Assert.assertEquals("3", response.getContentAsString()); 


} 
} 

私はあなたにも、私はCollectionではなくListを使用して、これでいくつかの運を持っていた​​

0

を使用することができると思います。私はListのためにStringConverterを作ることができませんでした。

@Provider 
public class CollectionConverter implements StringConverter<Collection<String>> { 

    public Collection<String> fromString(String string) { 
    if (string == null) { 
     return Collections.emptyList(); 
    } 
    return Arrays.asList(string.split(",")); 
    } 

    public String toString(Collection<String> values) { 
    final StringBuilder sb = new StringBuilder(); 
    boolean first = true; 
    for (String value : values) { 
     if (first) { 
     first = false; 
     } else { 
     sb.append(","); 
     } 
     sb.append(value); 
    } 
    return sb.toString(); 
    } 
} 

私はtoStringを私の頭からやった。確認のための単体テストを必ず記入してください。もちろん、Guavaを使用するとすべてが簡単になり、より明確になります。 JoinerSplitterを使用できます。本当に便利です。

0

ラッパーを単独で使用してください。何も必要ありません。

エンドポイントで

@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) 
@Path("/find") 
@GET 
MyResponse find(@QueryParam("ids") Wrapper ids); 

そして、あなたラッパー次のようになります。

関連する問題