本文目錄一覽:
Java反射的功能:從json到bean
為了實現非同步傳輸(Ajax),通常伺服器和瀏覽器之間的交互都是通過json來完成的。
客戶端(瀏覽器)執行相應的代碼,可以將獲取到的json通過使用prototype提供的evalJSON函數轉換成js對象。
java反射生成json如何去掉自帶屬性
org.codehaus.groovy.grails.plugins.web.api.ControllersDomainBindingApi@431a3fe1
這樣的現實無非就是ControllersDomainBindingApi 這個類沒有重寫toString方法 ,才出現這樣的情況
Java的json反序列化:Java數據類可以和json數據結構不一致嗎?
由於時間關係我也沒有寫全,這裡提供一個思路吧。代碼如下:
Account.java:
@Data
public class Account {
private int id;
private String name;
// @PowerfulAnnotation註解是我臆想的
@PowerfulAnnotation(“token.id”)
private String tokenId;
@PowerfulAnnotation(“token.key”)
private String key;
}
PowerfulAnnotation.java:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PowerfulAnnotation {
String value() default “”;
}
測試類Main.java:
public class Main {
public static void main(String[] args) throws Exception {
Account account = new Account();
String ori = “{\n” +
“\”id\”: 11111,\n” +
“\”name\”: \”小李\”,\n” +
“\”token\”: {\n” +
“\”id\”: 22222222,\n” +
“\”key\”: \”ddddddddd\”\n” +
“}\n” +
“}”;
Gson gson = new Gson();
//字元串json轉JsonObject
JsonObject jsonObject = gson.fromJson(ori, JsonObject.class);
//反射獲取目標對象屬性
for (Field field : account.getClass().getDeclaredFields()) {
String fieldName = field.getName();
Class fieldClass = field.getType();
System.out.print(“當前field名:[” + fieldName + “],”);
System.out.println(“當前field類型:[” + fieldClass + “]”);
Annotation annotation = field.getDeclaredAnnotation(PowerfulAnnotation.class);
//檢查是否有PowerfulAnnotation註解
if (annotation != null) {
PowerfulAnnotation powerful = (PowerfulAnnotation) annotation;
String powerfulValue = powerful.value();
System.out.println(“發現PowerfulAnnotation註解,值為:[” + powerfulValue + “]”);
String[] tmp = powerfulValue.split(“\\.”);
//聲明一個臨時JsonObject,將用於獲取下一層json對象
JsonObject tmpJson = jsonObject;
for (int i = 0; i tmp.length; i++) {
//目標值是在powerfulValue的最後一個欄位,例如powerfulValue為token.id的話,目標的值就是id,所以先獲取token這個jsonObject,並賦值給臨時tmpJson
if (i != tmp.length – 1) {
tmpJson = jsonObject.get(tmp[i]).getAsJsonObject();
} else {
//到達powerfulValue的最後一個欄位,檢查其類型,並賦值給目標對象
Object value = checkFieldType(tmpJson, tmp[i], fieldClass);
//從目標對象中獲取目標屬性
Field targetField = account.getClass().getDeclaredField(field.getName());
targetField.setAccessible(true);//解除私有限制
System.out.println(“將[” + powerfulValue + “]的值[” + value + “]賦給目標對象的[” + fieldName + “]”);
//將值賦值給目標屬性
targetField.set(account, value);
}
}
}
//屬性上沒有PowerfulAnnotation註解
else {
//檢查當前屬性的類型
Object value = checkFieldType(jsonObject, fieldName, fieldClass);
//從目標對象中獲取目標屬性
Field targetField = account.getClass().getDeclaredField(field.getName());
targetField.setAccessible(true);//解除私有限制
System.out.println(“直接將值[” + value + “]賦給目標對象的[” + fieldName + “]”);
//將值賦值給目標屬性
targetField.set(account, value);
}
System.out.println(“*********************************************\n”);
}
System.out.println(“目標對象最終值:” + account);
}
/**
* 檢查當前屬性的類型
* (這裡由於時間關係,我沒有寫全,只檢查了String、int、boolean類型,全類型應包括boolean、char、byte、short、int、long、float、double,你有時間自己補充一下)
*
* 如果發現當前屬性是一個對象,那麼應該將JsonObject轉換成對應的對象再返回(由於時間關係,這裡我也沒有試過,總之思路是這樣)
*/
private static Object checkFieldType(JsonObject field, String fieldName, Class fieldClass) {
if (fieldClass == String.class) {
return field.get(fieldName).getAsString();
}
if (fieldClass == int.class) {
return field.get(fieldName).getAsInt();
}
if (fieldClass == boolean.class) {
return field.get(fieldName).getAsBoolean();
}
return new Gson().fromJson(field.get(fieldName), fieldClass);
}
}
代碼還沒寫完,主要集中在沒有對JsonArray進行處理,當json串里包含數組時會報錯,另外一些沒寫完的我在注釋里寫了點,你可以參照一下。整體思路還是利用java反射機制進行。
以上代碼運行結果:
原創文章,作者:APIO,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/134746.html