You can achieve this by using Gson Library from Google and by creating a custom deserializer.
For Example : Consider an Employee class to which you want to deserialize into.
public class Employee {
private String name;
private String cell;
public Employee(String name, String cell) {
super();
this.name = name;
this.cell = cell;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCell() {
return cell;
}
public void setCell(String cell) {
this.cell = cell;
}
}
Write a custom deserializer as :
public class CapsDeserializer implements JsonDeserializer<Employee> {
@Override
public Employee deserialize(JsonElement json, Type arg1, JsonDeserializationContext arg2)
throws JsonParseException {
JsonObject jobject = json.getAsJsonObject();
try {
Employee emp = new Employee(
jobject.get(Employee.class.getDeclaredField("name").getName().toUpperCase()).getAsString(),
jobject.get(Employee.class.getDeclaredField("cell").getName().toUpperCase()).getAsString());
return emp;
} catch (NoSuchFieldException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Note : the field name are accessed by reflection and then converted into caps. Since the field names of the class are in small letters while the inputted json has field names in caps.
Sample program to execute :
public class GsonExampleApplication {
public static void main(String[] args) {
Gson gson = new Gson();
Employee test = new Employee("", "");
test.setCell("1234567891");
test.setName("abhishek");
System.out.println("" + gson.toJson(test));
String json = "{\"NAME\":\"abhishek\",\"CELL\":\"1234567891\"}";
FieldNamingStrategy f = gson.fieldNamingStrategy();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Employee.class, new CapsDeserializer());
Gson cgson = gsonBuilder.create();
Employee obj = cgson.fromJson(json, Employee.class);
System.out.println(obj.getName() + " " + obj.getCell());
}
}