【问题标题】:How to transfer a List of Primitive with Jersey + JAXB + JSON如何使用 Jersey + JAXB + JSON 传输原始列表
【发布时间】:2012-11-09 23:16:19
【问题描述】:

如果我转移具有 @XmlRoolElement 的类 ( MyClass ),此代码可以正常工作

客户

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

但是,如果我尝试传输一个原语,如字符串、整数、布尔值等...

客户

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

我得到了错误:

无法将类型“java.lang.Integer”编组为元素,因为它缺少 @XmlRootElement 注释

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

客户

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

服务器

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

有没有一种方法可以在不为每个原始类型创建包装类的情况下传输这种列表?还是我遗漏了一些明显的东西?

【问题讨论】:

    标签: java json list jaxb jersey


    【解决方案1】:

    我找到了一种解决方法,方法是手动控制 un-/marshalling,无需 Jersey。

    客户

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

    服务器

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

    还有我使用的 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);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-26
      • 2013-09-09
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多