2012-11-21 31 views
5

Mã này hoạt động tốt nếu tôi chuyển một lớp (MyClass) đã @XmlRoolElementLàm thế nào để chuyển một Danh sách nguyên thủy với Jersey + JAXB + JSON

Khách hàng

WebResource webResource = restClient.resource(getRessourceURL()); 
return webResource.get(new GenericType<List<MyClass>>(){}); 

Nhưng nếu tôi cố gắng để chuyển một nguyên thủy, giống như string, Integer, Boolean, vv ...

khách hàng

WebResource webResource = restClient.resource(getRessourceURL()); 
return webResource.get(new GenericType<List<Integer>>(){}); 

Tôi nhận được lỗi:

không thể marshal gõ "java.lang.Integer" như một yếu tố vì nó thiếu một chú thích @XmlRootElement

tôi nhận được chính xác kết quả tương tự khi gửi một thông số đơn vị yêu cầu của tôi:

khách hàng

WebResource webResource = restClient.resource(getRessourceURL()); 
return webResource.post(new GenericType<List<Integer>>(){}, Arrays.toList("1")); 

server

@GET 
@Path("/PATH") 
@Produces(MediaType.APPLICATION_JSON) 
public List<MyClass> getListOfMyClass(List<Integer> myClassIdList) 
{ 
    return getMyClassList(myClassIdList); 
} 

Có cách nào để tuyền loại danh sách mà không cần tạo một lớp wrapper cho mỗi một trong các loại nguyên thủy ?? Hoặc tôi thiếu một cái gì đó hiển nhiên?

Trả lời

1

Tôi đã tìm thấy một công việc xung quanh bằng cách kiểm soát un-/marshalling bằng tay, không có Jersey.

Khách hàng

WebResource webResource = restClient.resource(getRessourceURL()); 
return webResource.post(new GenericType<List<Integer>>(){}, JAXBListPrimitiveUtils.listToJSONArray(Arrays.toList("1"))); 

server

@GET 
@Path("/PATH") 
@Produces(MediaType.APPLICATION_JSON) 
public List<MyClass> getListOfMyClass(JSONArray myClassIdList) 
{ 
    return getMyClassList(JAXBListPrimitiveUtils.<Integer>JSONArrayToList(myClassIdList)); 
} 

Và lớp util tôi đã sử dụng:

import java.util.ArrayList; 
import java.util.List; 

import org.codehaus.jettison.json.JSONArray; 
import org.codehaus.jettison.json.JSONException; 

public class JAXBListPrimitiveUtils 
{ 

    @SuppressWarnings("unchecked") 
    public static <T> List<T> JSONArrayToList(JSONArray array) 
    { 
    List<T> list = new ArrayList<T>(); 
    try 
    { 
     for (int i = 0; i < array.length(); i++) 
     { 
     list.add((T)array.get(i)); 
     } 
    } 
    catch (JSONException e) 
    { 
     java.util.logging.Logger.getLogger(JAXBListPrimitiveUtils.class.getName()).warning("JAXBListPrimitiveUtils :Problem while converting JSONArray to arrayList" + e.toString()); 
    } 

    return list; 
    } 

    @SuppressWarnings("rawtypes") 
    public static JSONArray listToJSONArray(List list) 
    { 
    return new JSONArray(list); 
    } 
} 
Các vấn đề liên quan