2011-12-28 9 views
11

के लिए Gson Deserializer क्या किसी को Deserializer काम कर रहा है? मैं तत्व के बजाय "deserialize" विधि में पूर्ण JSON अभिव्यक्ति प्राप्त कर रहा हूँ ??java.util.Date

public static void main(String[] args) { 
    GsonBuilder gb = new GsonBuilder(); 
    gb.registerTypeAdapter(DummyObject.class, new JsonSerializer<Date>() { 
     public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { 
      System.out.println("serialize..."); 
      return new JsonPrimitive(DateUtil.toString(src)); 
     } 
    }); 
    gb.registerTypeAdapter(DummyObject.class, new JsonDeserializer<Date>() { 
     DateFormat format = DateFormat.getInstance(); 

     public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 
      if (!(json instanceof JsonPrimitive)) { 
       throw new JsonParseException("The date should be a string value"); 
      } 

      try { 
       return format.parse(json.getAsString()); 
      } catch (ParseException e) { 
       throw new JsonParseException(e); 
      } 
     } 
    }); 

    String jsonExp = "{\"createdDate\":\"2011-12-27T15:21:16\"}"; 
    Gson g = gb.create(); 
    DummyObject tf = g.fromJson(jsonExp, DummyObject.class); 

} 

उत्तर

40
Gson gson = new GsonBuilder() 
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssz") 
.create(); 
+2

अंत में छोटा 'z' आईएसओ स्वरूपित डेटाटाइम तारों के लिए एक मुद्दा हो सकता है क्योंकि टाइमज़ोन ज़ेड या +00: 00 हो सकता है जिसे सरलडेटाफॉर्मैट – Lucas

+0

द्वारा ठीक से संभाला नहीं जा सकता है, यह जानना अच्छा होगा कि वसंत को कॉन्फ़िगर कैसे करें, यह ऐसा करता है। – user1944491

+0

सही उत्तर ..... मतदान 1 – sonida

-2
मूल प्रश्न में कोड के साथ

, या तो Gson 1.7.1 या Gson 2.0 का उपयोग कर, मैं सब मिलता है "सूत्र में अपवाद" मुख्य "com.google.gson.JsonParseException: तिथि एक स्ट्रिंग होना चाहिए मूल्य "। यह वही है जो मैं कोड को करने के लिए लिखा था।

मुझे लगता है कि आप java.util.Date के लिए एक प्रकार एडाप्टर पंजीकृत करना चाहते हैं, और DummyObject के लिए नहीं। (इससे एक अलग त्रुटि होती है, लेकिन मुझे लगता है कि यह आप जो हासिल करने की कोशिश कर रहे हैं उसके करीब है। बेशक, मैं प्रश्न/कोड के इरादे के बारे में थोड़ा अनुमान लगा रहा हूं।)

या शायद आप चाहते हैं निम्न पंक्तियों के साथ deserialization तर्क बदलें, समझते हैं कि आप केवल JSON के दिनांक भाग को java.util.Date में deserialize करना चाहते हैं।

gb.registerTypeAdapter(DummyObject.class, new JsonDeserializer<Date>() 
{ 
    DateFormat format = DateFormat.getInstance(); 

    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) 
     throws JsonParseException 
    { 
    try 
    { 
     return format.parse(((JsonObject)json).get("createdDate").getAsString()); 
    } 
    catch (ParseException e) 
    { 
     throw new JsonParseException(e); 
    } 
    } 
}); 

आपको अभी भी (अधिक विशिष्ट) दिनांक पार्सिंग त्रुटि को हल करने की आवश्यकता होगी।

+0

तो JSON अभिव्यक्ति इसमें अन्य फ़ील्ड शामिल हैं जो "DummyObject" कहने के लिए मानचित्र करते हैं और फ़ील्ड में से एक को दिनांक के रूप में दर्शाया जाता है। – gpa

0

यहां आपको कस्टम Gson बिल्डर जो लगभग हर तारीख पैटर्न JodaTime का उपयोग कर संभालती है (यह बाहर कर सकते हैं अगर यह उपयोग करने के लिए, यह सिर्फ संभावनाओं का विस्तार नहीं करना चाहती)

public class MyGsonBuilder { 

    public static <T> List<T> toList(String json, Class<T> clazz) { 
     if (null == json) { 
      return null; 
     } 
     Gson gson = build(); 
     return gson.fromJson(json, new TypeToken<T>() { 
     }.getType()); 
    } 

    private static boolean enableLog = false; 


    private static void log(String log) { 
     if (enableLog) Log.d("DEBUG_GSON_TIME", log); 
    } 

    static List<SimpleDateFormat> knownPatterns = new ArrayList<>(Arrays.asList(
      new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"), 
      new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"), 
      new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss"), 
      new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"), 
      new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss") 
    )); 

    static JsonSerializer<Date> ser = new JsonSerializer<Date>() { 
     @Override 
     public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { 
      return new GsonBuilder().create().toJsonTree(buildIso8601Format().format(src)); 
     } 
    }; 


    static JsonDeserializer<Date> deser = new JsonDeserializer<Date>() { 

     @Override 
     public Date deserialize(JsonElement json, Type typeOfT, 
           JsonDeserializationContext context) throws JsonParseException { 
      Date date = null; 

      try { 
       // Take a try 
       String dateString = json.getAsJsonPrimitive().getAsString(); 
       log("deserialize date string = " + dateString); 
       date = buildOddFormat().parse(dateString); 
       log(" pattern (yyyy-MM-dd HH:mm:ss) = SUCCESS " + dateString + " = " + date.toString()); 
      } catch (Throwable t) { 
       // Loop on 
       log(" pattern (yyyy-MM-dd HH:mm:ss) = error = " + t.getMessage()); 
      } 

      if (date == null) { 
       try { 
        // Take a try 
        String dateString = json.getAsJsonPrimitive().getAsString(); 
        date = buildOldFormat().parse(dateString); 
        log(" pattern (MMM dd, yyyy HH:mm:ss) = SUCCESS " + dateString + " = " + date.toString()); 
       } catch (Throwable t) { 
        // Loop on 
        log(" pattern (MMM dd, yyyy HH:mm:ss) = error = " + t.getMessage()); 
       } 

      } 
      if (date == null) { 
       try { 
        // Take a try 
        String dateString = json.getAsJsonPrimitive().getAsString(); 
        date = buildVeryOldFormat().parse(dateString); 
        log(" pattern (MMM d, yyyy HH:mm:ss) = SUCCESS " + dateString + " = " + date.toString()); 
       } catch (Throwable t) { 
        // Loop on 
        log(" pattern (MMM d, yyyy HH:mm:ss) = error = " + t.getMessage()); 
       } 

      } 
      if (date == null) 

       for (SimpleDateFormat pattern : knownPatterns) { 
        try { 
         // Take a try 
         if (!pattern.toPattern().contains("Z")) 
          pattern.setTimeZone(TimeZone.getTimeZone("UTC")); 
         String dateString = json.getAsJsonPrimitive().getAsString(); 
         if (!pattern.toPattern().contains("Z")) 
          pattern.setTimeZone(TimeZone.getTimeZone("UTC")); 
         date = new Date(pattern.parse(dateString).getTime()); 
         log(" pattern (" + pattern.toPattern() + ") = SUCCESS " + dateString + " = " + date.toString()); 
         break; 
        } catch (Throwable t) { 
         // Loop on 
         log(" pattern (" + pattern.toPattern() + ") = error = " + t.getMessage()); 
        } 
       } 

//   } 
      if (date == null) { 
       try { 
        date = new Date(json.getAsJsonPrimitive().getAsLong()); 
        log(" Joda = SUCCESS " + json.getAsJsonPrimitive().getAsString() + " = " + date.toString()); 
       } catch (Throwable t) { 
        log(" pattern (Long) = error = " + t.getMessage()); 
       } 
      } 
      if (date == null) { 
       try { 
        date = DateFormat.getInstance().parse(json.getAsJsonPrimitive().getAsString()); 
        log(" Joda = SUCCESS " + json.getAsJsonPrimitive().getAsString() + " = " + date.toString()); 
       } catch (Throwable t) { 
        log(" pattern (DateFormat.getInstance().parse()) = error = " + t.getMessage()); 
       } 
      } 
      if (date == null) { 
       DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); 
       try { 
        String dateString = json.getAsJsonPrimitive().getAsString(); 
        date = fmt.parseDateTime(dateString).toDate(); 
        log(" Joda = SUCCESS " + dateString + " = " + date.toString()); 
       } catch (Throwable t) { 
        // Loop on 
        log(" Joda error = " + t.getMessage()); 
        Crashlytics.logException(new Throwable("NON PARSABLE DATE!!! = " + json.toString())); 
       } 
      } 

      if (date == null) 
       date = new Date(); 

      return date; 
     } 
    }; 

    private static DateFormat buildIso8601Format() { 
     DateFormat iso8601Format = new SimpleDateFormat(
       "yyyy-MM-dd'T'HH:mm:ss.SSSZ"); 
     return iso8601Format; 
    } 

    private static DateFormat buildOddFormat() { 
     DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
     iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC")); 
     return iso8601Format; 
    } 

    private static DateFormat buildOldFormat() { 
     DateFormat iso8601Format = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss"); 
     iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC")); 
     return iso8601Format; 
    } 

    private static DateFormat buildVeryOldFormat() { 
     DateFormat iso8601Format = new SimpleDateFormat("MMM d, yyyy HH:mm:ss"); 
     iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC")); 
     return iso8601Format; 
    } 

    static public Gson build() { 
     Gson gson = new GsonBuilder() 
       //.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") 
       .registerTypeAdapter(Date.class, deser) 
       .registerTypeAdapter(Date.class, ser) 
       .excludeFieldsWithoutExposeAnnotation() 
       .create(); 
     return gson; 
    } 
} 
संबंधित मुद्दे