2017-11-09 1 views
0
public class MyClass{ 
    @SerializedName("hello") 
    private String hello; 

    @SerializedName("world") 
    private String world 

    @SerializedName("dynamic") 
    private String dynamic; 
} 

모든 동적 이름을 변수 dynamic으로 구문 분석 할 수 있기를 원합니다. 예 :Gson - Genericate SerializedName 얻기

{ "안녕하세요" "안녕하세요", "세계": "세계", "dynamic123": "QWERTY"}

{ "안녕하세요" "안녕하세요", "세계" "세계", "dynamic345": "asdfgh"}

{ "안녕하세요"

을 : "안녕하세요", "세계": "세계", "dynamic567": "zxcvbn"}

어떻게 나는 이것을 성취합니까?

답변

2

당신의 MyClass에 대한

public class MyClassDeSerializer implements JsonDeserializer<MyClass> { 
    @Override 
    public MyClass deserialize(JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 
     MyClass myClass = new MyClass(); 

     for (Map.Entry<String, JsonElement> property : jsonElement.getAsJsonObject().entrySet()) { 
      if (property.getKey().contains("dynamic")) { 
       myClass.setDynamic(property.getValue().getAsString()); 
      } 
      else if (property.equals("hello")) { 
       myClass.setHello(property.getValue().getAsString()); 
      } 
      else if (property.getKey().equals("world")) { 
       myClass.setWorld(property.getValue().getAsString()); 
      } 
     } 
     return myClass; 
    } 
} 

을 사용자 정의 GSON Deserilizer를 만들고이 클래스

Gson gson = new GsonBuilder().registerTypeAdapter(MyClass.class , new MyClassDeSerializer()).create(); 

에게

MyClass result = gson.fromJson(json, MyClass.class); 
Deserilize

를 등록하여 GSON 만들기