我試圖通過長數組與網隊:REST - 如何在Jersey中傳入長參數數組?
在客戶端我已經嘗試類似的東西:
@GET
@Consume("text/plain")
@Produces("application/xml)
Response getAllAgentsById(@params("listOfId") List<Long> listOfId);
有沒有意識到這樣的事情的方法嗎?
在此先感謝!
我試圖通過長數組與網隊:REST - 如何在Jersey中傳入長參數數組?
在客戶端我已經嘗試類似的東西:
@GET
@Consume("text/plain")
@Produces("application/xml)
Response getAllAgentsById(@params("listOfId") List<Long> listOfId);
有沒有意識到這樣的事情的方法嗎?
在此先感謝!
如果你只是需要傳遞數組而不會有任何問題。但我可能會通過逗號分隔的字符串來傳遞。 (123,233,2344,232),然後拆分字符串並將其轉換爲long。
如果不是,我建議你使用Json序列化。如果您使用的是java客戶端,那麼google gson是一個不錯的選擇。在客戶端,我將對我的列表進行編碼:
List<Long> test = new ArrayList<Long>();
for (long i = 0; i < 10; i++) {
test.add(i);
}
String s = new Gson().toJson(test);
並將此字符串作爲post參數傳遞。在服務器端,我會像這樣解碼。
Type collectionType = new TypeToken<List<Long>>() {
} // end new
.getType();
List<Long> longList = new Gson().fromJson(longString,
collectionType);
如果你想堅持到「應用程序/ XML」的格式,避免JSON格式,你應該換這個數據到JAXB註釋的對象,因此澤西可以使用內置的MessageBodyWriter/MessageBodyReader。
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public ListOfIds{
private List<Long> ids;
public ListOfIds() {}
public ListOfIds(List<Long> ids) {
this.ids= ids;
}
public List<Long> getIds() {
return ids;
}
}
在客戶端(使用Jersey客戶端)
// get your list of Long
List<Long> list = computeListOfIds();
// wrap it in your object
ListOfIds idList = new ListOfIds(list);
Builder builder = webResource.path("/agentsIds/").type("application/xml").accept("application/xml");
ClientResponse response = builder.post(ClientResponse.class, idList);
可能,我錯明白你的問題。(我以前的解決方案仍然有效)。但通常當你想傳遞數組和其他複雜的數據結構時,最好使用某種序列化機制。我通常使用Json格式進行通信。讓我知道,如果這是你想要的。 – 2011-02-02 18:13:15