public class Main {
public static void main(String[] args){
JSONObject jo = new JSONObject();
jo.put("a",1);
try {
Ob ob = (Ob)JsonUtil.jsonToObject(new Ob(),jo);
System.out.println(ob.getA());
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
class JsonUtil{
public static Object jsonToObject(Object object,JSONObject jsonObject) throws NoSuchFieldException, IllegalAccessException {
Class ca = object.getClass();
Iterator<String> iterator = jsonObject.keys();
String key;
while (iterator.hasNext()){
key = iterator.next();
Field field = ca.getDeclaredField(key);
field.setAccessible(true);
if(field.getName().equals(key)){
field.set(object,jsonObject.get(key));
}
}
return object;
}
}
class Ob{
private int a;
private String b;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
}