Json-Jersey无法解组参数化的根列表

时间:2016-03-06 14:00:17

标签: java json list jersey

最近我尝试编写泛型函数,它将使用jesrey-json-1.8将json响应从API转换为对象。我发现它适用于列表。 它可以配置还是jersey-json只能处理参数化类型?

这有效:

@XmlRootElement
public static class ListWrapper {       
    @XmlElement
    public List<Advertiser> advertisers; 
}

@Test
public void testListFromJson() throws ParseException, JAXBException {
    String str = "{\"advertisers\":[{\"advertiser_id\":\"1\",\"name\":\"adidas\",\"owner_id\":\"1\"},{\"advertiser_id\":\"2\",\"name\":\"bdidas\",\"owner_id\":\"2\"}]}";
    ListWrapper list = new ListWrapper();
    String json = str; //"{\"list\":" + json + "}";
    JSONJAXBContext jaxbContext = new JSONJAXBContext( list.getClass() );
    JSONUnmarshaller unmarshaller = jaxbContext.createJSONUnmarshaller();
    list = unmarshaller.unmarshalFromJSON( new StringReader( json ), list.getClass() );         
}

但是,我需要使用参数化列表,因为我有几个API调用返回列表:&#39; api / advertisers / all&#39;,&#39; api / permissions / all&#39;,&#39; API /活动/所有&#39;等等,但这不起作用:

@XmlRootElement
public static class ListWrapper<T> {

    @XmlElement
    public List<T> advertisers; 
}

@SuppressWarnings("unchecked")
@Test
public void testListFromJson() throws ParseException, JAXBException {
    String str = "{\"advertisers\":[{\"advertiser_id\":\"1\",\"name\":\"adidas\",\"owner_id\":\"1\"},{\"advertiser_id\":\"2\",\"name\":\"bdidas\",\"owner_id\":\"2\"}]}";
    ListWrapper<Advertiser> list = new ListWrapper<Advertiser>();
    String json = str; //"{\"list\":" + json + "}";
    JSONJAXBContext jaxbContext = new JSONJAXBContext( list.getClass(), Advertiser.class );
    JSONUnmarshaller unmarshaller = jaxbContext.createJSONUnmarshaller();
    list = unmarshaller.unmarshalFromJSON( new StringReader( json ), list.getClass() );         
}

XML问题几乎相似 (例如Unmarshalling generic list with JAXB),但是这个解决方案不适用于jersey-json,或者也许仅适用于我的情况,其中list是根元素:

@XmlRootElement
public static class ListWrapper<T> {

  private List<T> items;

  public ListWrapper() {
    items = new ArrayList<T>();
  }

  public ListWrapper(List<T> items) {
    this.items = items;
  }

  @XmlAnyElement(lax=true)
  public List<T> getItems() {
    return items;
  }
}

String json =  "{\"items\":[{\"advertiser_id\":\"1\",\"name\":\"adidas\",\"owner_id\":\"1\"},{\"advertiser_id\":\"2\",\"name\":\"bdidas\",\"owner_id\":\"2\"}]}"; 
    JSONJAXBContext context = new JSONJAXBContext(Advertiser.class, ListWrapper.class);
    JSONUnmarshaller unmarshaller = context.createJSONUnmarshaller();

    ListWrapper<Advertiser> wrapper = (ListWrapper<Advertiser>)unmarshaller.unmarshalFromJSON( new StringReader( json ), ListWrapper.class );

1 个答案:

答案 0 :(得分:0)

No goo solution was found, so I did it in an ugly, but working way: 1. Remove brackets from start and end of json string 2. Split by ',' 3. Pass over the array from (2) and make unmarshalling call