JSON字符串
{
"data":{
"PD01":{
"KEY1":"1",
"KEY2":"2",
"KEY3":"3"
},
"PD02":{
"KEY4":"4",
"KEY5":"5"
},
"PD03":{
"KEY6":"6"
}
}
}
实体类
@Data
public class ReflectionObj {
private String KEY1;
private String KEY3;
private String KEY4;
private String KEY6;
private String KEY7;
}
关键步骤
1.遍历json字符串
String jsonkey : jsonObject.keySet()
2.获取实体类字段
Field field = reflectionclazz.getDeclaredField(jsonkey);
3.赋值
field.set(reflectionObj,jsonObject.getString(jsonkey));
参考demo
public class Reflection {
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
JSONObject jsonObject = JSON.parseObject("{\"data\":{\"PD01\":{\"KEY1\":\"1\",\"KEY2\":\"2\",\"KEY3\":\"3\"},\"PD02\":{\"KEY4\":\"4\",\"KEY5\":\"5\"},\"PD03\":{\"KEY6\":\"6\"}}}");
Class reflectionclazz = ReflectionObj.class;
Object reflectionObj = reflectionclazz.newInstance();
Reflection reflection = new Reflection();
if(jsonObject.containsKey("data")){
JSONObject dataJson = jsonObject.getJSONObject("data");
if(dataJson.containsKey("PD01")){
reflection.savedata(reflectionclazz,reflectionObj,dataJson,"PD01");
}
if(dataJson.containsKey("PD02")){
reflection.savedata(reflectionclazz,reflectionObj,dataJson,"PD02");
}
if(dataJson.containsKey("PD03")){
reflection.savedata(reflectionclazz,reflectionObj,dataJson,"PD03");
}
System.out.println(JSONArray.toJSONString(reflectionObj));
}
}
public void savedata(Class reflectionclazz,Object reflectionObj,JSONObject dataJson,String key) {
JSONObject jsonObject = dataJson.getJSONObject(key);
for (String jsonkey : jsonObject.keySet()) {
try {
Field field = reflectionclazz.getDeclaredField(jsonkey);
field.setAccessible(true);
field.set(reflectionObj,jsonObject.getString(jsonkey));
} catch (Exception e) {
continue;
}
}
}
}
打印结果
{"kEY1":"1","kEY3":"3","kEY4":"4","kEY6":"6"}