如何使用Jersey + JAXB + JSON传输基元列表

vie*_*che 5 java json list jaxb jersey

如果我传输一个具有@XmlRoolElement的类(MyClass),此代码可以正常工作

客户

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

但是,如果我尝试传输一个原语,如String,Integer,Boolean等...

客户

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

我收到错误:

无法封装类型"java.lang.Integer"作为元素,因为它缺少@XmlRootElement注释

在向我的请求发送实体参数时,我得到完全相同的结果:

客户

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

服务器

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

有没有办法转移这种列表而不为每个这些原始类型创建包装类?还是我错过了一些明显的东西?

vie*_*che 1

我找到了一种解决方法,可以在没有泽西的情况下手动控制取消/编组。

客户

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

服务器

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

和我使用的 util 类:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)