2015-01-28 2 views
0

후 자동 호출 방법 내가 가진 클래스 :GSON 필드 명명 예를 들어, 인스턴스

public static class News implements Comparable<News>, Parcelable { 
     static DateFormat df = new SimpleDateFormat("dd-MM-yyyy"); 

     @SerializedName("Published") 
     public String DateStr; 

     MyDate date; 

     public void callItAfterInstantiate(){ 
      if(date == null){ 
       java.util.Date parsed; 
       try { 
        parsed = df.parse(DateStr); 
        date = new MyDate(parsed.getTime()); 
       } catch (ParseException e) { 
        e.printStackTrace(); 
       } 

      } 
     } 

     {...} 
} 

내가 사용하여 인스턴스화 할 수 GSON :

News news = gson.fromJson(json, News.class); 

그러나 날짜 = NULL;

인스턴스화 후 callItAfterInstantiate을 자동 호출해야합니다. 가능한가? 예를 들어 MyDate 필드. 실제 프로젝트에는 생성 후 자동 호출이되어야하는 또 다른 논리가있을 수 있습니다.

또는 가능한 한 가지 해결책은 인스턴스화 후 메서드를 직접 호출하는 것입니다.

news.callItAfterInstantiate(); 
+0

안녕하세요 도움이 될 것입니다 a very good tutorial

public class NewsDeserializer implements JsonDeserializer<News> { public final static String TAG = "NewsDeserializer"; @Override public News deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { //json object is complete final JsonObject jsonObj = json.getAsJsonObject(); // Log.i(TAG, jsonObj.toString()); News news = new News(); //parse your data here using JsonObject see the documentation it's pretty simple news.callItAfterInstantiate(); return news; } } //then to parse you data final GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(News.class, new NewsDeserializer()); final Gson gson = gsonBuilder.create(); News news = gson.fromJson(json, News.class); 

희망, json에서 Date 객체로 날짜 문자열을 파싱 할 필요가 없습니까? 그렇다면 어떻게 할 지에 대한 힌트를 줄 수 있습니다. – medhdj

+0

@medhdj는 좋을 것입니다. – Suvitruf

답변

1

좋아요, 여기에 첫 번째 날짜가

public static class News implements Comparable<News>, Parcelable { 
     public static DateFormat df = new SimpleDateFormat("dd-MM-yyyy"); 


     @SerializedName("Published") 
     Date date; 
//..... 
} 

//then you parse your data like this 
final GsonBuilder gsonBuilder = new GsonBuilder(); 
//use your date pattern 
gsonBuilder.setDateFormat(df.toPattern()); 
final Gson gson = gsonBuilder.create(); 
News news = gson.fromJson(json, News.class); 

두 번째 솔루션을 사용하면 JsonDeserializer 오버라이드 (override)하는 있어야에 대한 news.callItAfterInstantiate();의 사용 될 개체를 구문 분석하는 방법을 기본 GSON 파서를 말할 것이다 그렇게 할 수있는 방법은 2 가지입니다 이

+0

이 JSON에는 다른 데이터 형식의 데이터가 있습니다./ – Suvitruf

+0

아, MyDate 클래스에 대한 디시리얼라이저를 정의하여 등록 할 수 있습니다. 우리가 NewsDeserializer에서했던 것처럼. 또는 MyDate 개체를 만드는 String 날짜를 구문 분석 한 후 NewsDeserializer (두 번째 솔루션) – medhdj