Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transfer a List of Primitive with Jersey + JAXB + JSON

This code works fine if I transfer a class ( MyClass ) that has @XmlRoolElement

Client

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

But if I try to transfer a primitive, like String, Integer, Boolean, etc...

Client

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

I am getting the error :

unable to marshal type "java.lang.Integer" as an element because it is missing an @XmlRootElement annotation

I get exactly the same result when sending an entity parameter to my request:

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

Is there a way to tranfer this kind of list without creating a wrapper class for each of these primitive type?? Or am I missing something obvious?

like image 299
vieillebranche Avatar asked Nov 12 '22 17:11

vieillebranche


1 Answers

I've found a work around by controlling the un-/marshalling by hand, without 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) );
}

And the util class I used :

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);
  }
}
like image 139
vieillebranche Avatar answered Dec 04 '22 10:12

vieillebranche