猿问

Jackson和泛型参考

我想将jackson json库用于通用方法,如下所示:


public MyRequest<T> tester() {

    TypeReference<MyWrapper<T>> typeRef = new TypeReference<MyWrapper<T>>();  

    MyWrapper<T> requestWrapper = (MyWrapper<T>) JsonConverter.fromJson(jsonRequest, typeRef);

    return requestWrapper.getRequest();

}

...


public class MyWrapper<T> {


    private MyRequest<T> request;


    public MyRequest<T> getRequest() {

        return request;

    }


    public void setRequest(MyRequest<T> request) {

        this.request = request;

    }

}



 public class MyRequest{

     private List<T> myobjects;


     public void setMyObjects(List<T> ets) {

         this.myobjects = ets;

     }


     @NotNull

     @JsonIgnore

     public T getMyObject() {

         return myobjects.get(0);

     }

}

现在的问题是,当我调用请求对象内部的getMyObject()时,杰克逊将嵌套的自定义对象作为LinkedHashMap返回。有什么方法可以指定需要返回T对象吗?例如:如果我发送了类型为Customer的对象,则应该从该List?返回Customer。


谢谢。


幕布斯7119047
浏览 466回答 3
3回答

料青山看我应如是

“ JavaType”有效!我试图将json字符串中的列表解组(反序列化)为ArrayList java Objects,并且从现在开始一直在努力寻找解决方案。下面是最终给我解决方案的代码。码:JsonMarshallerUnmarshaller<T> {&nbsp; &nbsp; T targetClass;&nbsp; &nbsp; public ArrayList<T> unmarshal(String jsonString) {&nbsp; &nbsp; &nbsp; &nbsp; ObjectMapper mapper = new ObjectMapper();&nbsp; &nbsp; &nbsp; &nbsp; AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();&nbsp; &nbsp; &nbsp; &nbsp; mapper.getDeserializationConfig()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .withAnnotationIntrospector(introspector);&nbsp; &nbsp; &nbsp; &nbsp; mapper.getSerializationConfig()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .withAnnotationIntrospector(introspector);&nbsp; &nbsp; &nbsp; &nbsp; JavaType type = mapper.getTypeFactory().&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; constructCollectionType(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ArrayList.class,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; targetclass.getClass());&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Class c1 = this.targetclass.getClass();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Class c2 = this.targetclass1.getClass();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ArrayList<T> temp = (ArrayList<T>)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mapper.readValue(jsonString,&nbsp; type);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return temp ;&nbsp; &nbsp; &nbsp; &nbsp; } catch (JsonParseException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; } catch (JsonMappingException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return null ;&nbsp; &nbsp; }&nbsp;&nbsp;}
随时随地看视频慕课网APP

相关分类

Java
我要回答