2017-06-21 8 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

あなたはそのためにリフレクションを使用することができますが、キーは変数名と同じままになります。 jsonを作るためにbeanクラスと同じことをやっています。

希望すると助かります。

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; 
} 
関連する問題