简体   繁体   中英

Java generics and jackson mapper

Hi I have the following classes:

public class MyRequest {
}

and

public class MyResponse {
}

and

public class Request<T> {
private String code;
private T request;

public setCode(String code) {
   this.code = codel
  }

public setRequest(T request) {
   this.request = request
   }
}

and following service request method:

public MyResponse getMyResponse(Request<MyRequest> myRequest) {
//process
try {
    ObjectMapper mapper = new ObjectMapper();
    String jsonInString = mapper.writeValueAsString(myRequest);
    System.out.println(jsonInString);
  } catch(Exception exp) {}
}

and following Json request is sending from JavaScript;

{
   "code":"TESTCODE",
   "request":null 
}

After I send the request I an getting an Invalid Json error. Can anyone tell me what is wrong with my request Json or something else is wrong..?

By any chance are you using the model 'Request' as an inner class. If yes,

  • just try using the modifier static with 'Request'.
  • or rather move out the model 'Request' to a separate class

Non-static Inner classes by design contain a reference to the outer-class, which does cause problems in deserialization.

http://www.cowtowncoder.com/blog/archives/2010/08/entry_411.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM