2017-06-21 93 views
0

我想將Java POJO類轉換爲JSON。不過,我需要在JSON中更改鍵名。例如:如何編組/解組Java到Json?

class Employee { 
    private int empId; 
    private String empName; 
} 

的Json應該是:{ "EMP_ID" : "101", "EMP_NAME" : "Tessst" }

我發現GSON和其他圖書館要做到這一點,但我怎樣才能改變像地圖empId => EMP_ID的JSON關鍵的名字嗎?

回答

1

可以在GSON使用@SerializedName註釋:

class Employee { 
    @SerializedName("EMP_ID") 
    private int empId; 
    @SerializedName("EMP_NAME") 
    private String empName; 
} 
+0

非常感謝:) ......這個作品.. – Sid

0

您可以使用反射爲,但按鍵將保持相同的變量名。 我正在做與bean類相同的json。

希望它會有所幫助。

public static String getRequestJsonString(Object request,boolean withNullValue) { 

    JSONObject jObject = new JSONObject(); 

    try { 
     if (request != null) { 
      for (Map.Entry<String, String> row : mapProperties(request,withNullValue).entrySet()) { 

       jObject.put(row.getKey(), row.getValue()); 
      } 
     } 

     Log.v(TAG, jObject.toString()); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return jObject.toString(); 
} 


public static Map<String, String> mapProperties(Object bean,boolean withNullValue) throws Exception { 
    Map<String, String> properties = new HashMap<>(); 
    try { 
     for (Method method : bean.getClass().getDeclaredMethods()) { 
      if (Modifier.isPublic(method.getModifiers()) 
        && method.getParameterTypes().length == 0 
        && method.getReturnType() != void.class 
        && method.getName().matches("^(get|is).+") 
        ) { 
       String name = method.getName().replaceAll("^(get|is)", ""); 
       name = Character.toLowerCase(name.charAt(0)) + (name.length() > 1 ? name.substring(1) : ""); 

       Object objValue = method.invoke(bean); 

       if (objValue != null) { 
        String value = String.valueOf(objValue); 
        //String value = method.invoke(bean).toString(); 
        properties.put(name, value); 
       } else { 

        if (withNullValue) 
        { 
         properties.put(name, ""); 
        } 
       } 

      } 
     } 
    } catch (IllegalAccessException e) { 
     e.printStackTrace(); 
    } catch (IllegalArgumentException e) { 
     e.printStackTrace(); 
    } catch (InvocationTargetException e) { 
     e.printStackTrace(); 
    } 
    return properties; 
}