I have a Java Web application with multiple web modules. One will be acting as server and other module is acting as client, both deployed in different servers. Client app will call server app through rest service to get and save data. From server I am getting a JSON string and I'm trying to convert it to object with Generic types.
Here is my object
public class MyObject<T> {
private String name;
private List<T> list;
private final Class<T> referenceType;
@JsonCreator
public MyObject(@JsonProperty("referenceType") Class<T> referenceType) {
this.referenceType = referenceType;
list = new ArrayList<T>();
}
public Class<T> getReferenceType() {
return this.referenceType;
}
//getter and setter
}
In the server I am setting the object in following way
public String getAll(Long key) {
List<SomeObject> list = someObjectDao.getAll(key);
MyObject<SomeObject> myObject = new MyObject<SomeObject>(
SomeObject.class);
appObject.setList(list);
JSONObject jsonget = new JSONObject(myObject);
return jsonget.toString();
}
In the client app, I am getting the JSON string like this
{"name":"someName","referenceType":"class com.pkg.model.SomeObject","list":[{list - index - 0},{list - index-1}]}
And I am trying to convert the string to MyObject type in following way
private MyObject readJson(String output) throws Exception {
return new ObjectMapper().readValue(output,
new TypeReference<MyObject>() {
});
}
But I'm getting following exception,
Can not construct instance of java.lang.Class, problem: class com.pkg.model.SomeObject
at [Source: java.io.StringReader@4f906bf5; line: 1, column: 151]
How can I convert the JSON string to object?
Thanks.
Your client side is OK, the JSON you're reading in is not valid
the following would deserialize properly
"referenceType":"com.pkg.model.SomeObject"
than you'll be stuck with the list part.
Setting the server side to use jackson, e.g.
return new ObjectMapper().writeValueAsString(myObject);
would fix your issue
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments