I am currently working on a REST based application and need to convert a json object to a class. The problem is that class is from a third party library and I do not have access to the source file. Further the properties in the java object does not match to the getter/setters in the class(does not follow the java bean convention). For example if I try to deserialize the following json to a SimpleObject I get nulls instead of the actual data.
JSON input:
{
name: 'Test',
id: '1'
}
Java class to deserialize to
public class SampleObject {
private String myName;
private Long myId;
public Long getId() {
return this.myId;
}
public String getName() {
return this.myName;
}
.. // setters
}
Test class
public class TestGson {
public static void main(final String[] args) {
final Gson gson = new Gson();
final SampleObject smapleObject = gson.fromJson("{"
+ "name:'Test',"
+ "id: 1"
+ "}", SampleObject.class);
System.out.println(smapleObject.getName());
System.out.println(smapleObject.getId());
}
}
Result:
null
null
Expected:
Test
1
The problem is that gson uses the properties to deserialize the json whereas my requirement is to use the getter and setters.The class has getter and setters for all the properties and should not have any properties that does not have one.
Is there any other simple json library that I can use to achieve this without modifying the existing class(Cannot add annotations as the source is not available). I had a look at Jackson but it seems to add a bit complexity to do such a simple task and my team mates are not happy with it.
Jackson can do the exact thing and the syntax is also almost same.
E.g.:
POJO class :