2012-01-30 2 views
1

Gson으로 객체를 비 직렬화하는 동안 암호 필드 값을 XXX으로 바꾸려면 어떻게해야합니까? 나는이 게시물을 발견 : Gson: How to exclude specific fields from Serialization without annotations 기본적으로 필드를 건너 뜁니다. 이 옵션이 될 것입니다,하지만 난 아직도 내가이 시도 XXXjava gson 직렬화 중에 암호 값 바꾸기

으로 값을 대체하는 것을 선호 :

GsonBuilder builder = new GsonBuilder().setPrettyPrinting(); 
builder.registerTypeAdapter(String.class, new JsonSerializer<String>(){ 

    @Override public JsonElement serialize(String value, Type arg1, JsonSerializationContext arg2){ 
     // could not find a way to determine the field name  
     return new JsonPrimitive(value); 
    } 
}); 

불행히도,이 필드의 이름을 확인할 수 없습니다. 다른 옵션이 있습니까?

저는 Gson을 사용하여 일부 개체를 "꽤"로깅합니다. 따라서 로그를 읽는 동안 서식을 고민 할 필요가 없습니다.

+1

public class User { private static final Gson gson = new Gson(); public String name; public String password; public User(String name, String pwd){ this.name = name; this.password = pwd; } @Override protected Object clone() throws CloneNotSupportedException { return new User(this.name, this.password); } public static void main(String[] aa){ JsonSerializer<User> ser = new JsonSerializer<User>() { @Override public JsonElement serialize(User u, Type t, JsonSerializationContext ctx) { try { User clone = (User)u.clone(); clone.password = clone.password.replaceAll(".","x"); return (gson.toJsonTree(clone, User.class)); } catch (CloneNotSupportedException e) { //do something if you dont liek clone. } return gson.toJsonTree(u, User.class); } }; Gson g = new GsonBuilder().registerTypeAdapter(User.class, ser).create(); System.out.println(g.toJson(new User("naishe", "S3cr37"))); } } 

는에 연재 가져옵니다 JSON에 객체; 또는 그 반대? – Nishant

+0

직렬화 할 때 암호를 숨길 확률이 더 높습니다. 암호가 누출 될 가능성이 있기 때문입니다. –

+0

안녕하세요 @Nishant, 네, 방향을위한 암호를 마스크하고 싶습니다 => json (문자열) 정보를 기록 할 수 있습니다. 고맙습니다. 콘 – kon

답변

2

이 답변을 게시하는 동안 나는 꽤 절름발이입니다. 하지만 직렬화하기 전에 기본적으로 Java 객체를 복사하고 변경하는 것이 가능합니다. 당신은 그냥 일반적으로 직렬화, 복제 단계를 건너 뛰고 다음 암호를 대체 할 수

{"name":"naishe","password":"xxxxxx"} 
3

: 자바를 변환하는 동안 암호를 마스크 할

public JsonElement serialize(User u, Type t, JsonSerializationContext ctx) { 
      JsonObject obj = new Gson().toJsonTree(u).getAsJsonObject(); 
      obj.remove("password"); 
      obj.add("password", new JsonPrimitive("xxxxx"); 
      return obj; 
}