2012-11-21 17 views
5

Questo codice funziona bene se trasferisco una classe (MyClass) che ha @XmlRoolElementCome trasferire un elenco di Primitive con Jersey + JAXB + JSON

client

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

Ma se provo per trasferire un primitivo, come String, Integer, booleano, ecc ...

client

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

sto ottenendo l'errore:

grado di maresciallo tipo "java.lang.Integer" come un elemento perché manca un'annotazione @XmlRootElement

ottengo esattamente lo stesso risultato quando si invia un parametro di un'entità alla mia richiesta:

client

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'è un modo per tranfer questo tipo di lista senza creare una classe wrapper per ciascuno di questi tipo primitivo ?? O mi manca qualcosa di ovvio?

risposta

1

Ho trovato un modo per aggirare controllando lo smistamento manuale a mano, senza Jersey.

client

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)); 
} 

E la classe util ho usato:

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); 
    } 
} 
Problemi correlati