2014-04-03 6 views
9

sto usando RestTemplete per ottenere i dati JSON da un API REST e sto usando GSON per analizzare i dati dal formato JSON di opporsicom.google.gson.JsonSyntaxException quando si cerca di analizzare Data/Ora in JSON

Gson gson = new Gson(); 

restTemplate = new RestTemplate(); 
restTemplate.getMessageConverters().add(new GsonHttpMessageConverter()); 
restTemplate.getMessageConverters().add(new StringHttpMessageConverter()); 

List<Appel> resultList = null; 

resultList = Arrays.asList(restTemplate.getForObject(urlService, Appel[].class)); 

ma ottengo questo problema con Data, che cosa devo fare ..

Could not read JSON: 1382828400000; nested exception is com.google.gson.JsonSyntaxException: 1382828400000 

mia Pojo che contiene altri POJO in esso del corpo

public class Appel implements Serializable { 

    private Integer numOrdre; 
    private String reference; 
    private String objet; 
    private String organisme; 
    private Double budget; 
    private Double caution; 
    private Date dateParution; 
    private Date heureParution; 
    private Date dateLimite; 
    private Date heureLimite; 
    private List<Support> supportList; 
    private Ville villeid; 
    private Categorie categorieid; 

    public Appel() { 
    } 

    public Appel(Integer numOrdre, String reference, String objet, String organisme, Date dateParution, Date heureParution, Date dateLimite) { 
     this.numOrdre = numOrdre; 
     this.reference = reference; 
     this.objet = objet; 
     this.organisme = organisme; 
     this.dateParution = dateParution; 
     this.heureParution = heureParution; 
     this.dateLimite = dateLimite; 
    } 

questo è THS json restituito dal mio API

[ 
    { 
     "numOrdre": 918272, 
     "reference": "some text", 
     "objet": "some text", 
     "organisme": "some text", 
     "budget": 3000000, 
     "caution": 3000000, 
     "dateParution": 1382828400000, 
     "heureParution": 59400000, 
     "dateLimite": 1389657600000, 
     "heureLimite": 34200000, 
     "supportList": 
     [ 
      { 
       "id": 1, 
       "nom": "some text", 
       "dateSupport": 1384732800000, 
       "pgCol": "013/01" 
      }, 
      { 
       "id": 2, 
       "nom": "some text", 
       "dateSupport": 1380236400000, 
       "pgCol": "011/01" 
      } 
     ], 
     "villeid": 
     { 
      "id": 2, 
      "nom": "Ville", 
      "paysid": 
      { 
       "id": 1, 
       "nom": "Pays" 
      } 
     }, 
     "categorieid": 
     { 
      "id": 1, 
      "description": "some text" 
     } 
    }, 
    ..... 
] 
+0

cosa fa il tuo JSON assomiglia? Come è il tuo pojo? –

+0

Stai provando a pubblicare un messaggio lungo. – rpax

+0

Questi valori, '1384732800000', sembrano timestamp. Gson non è configurato per analizzare le date con i timestamp. Dovrai configurarlo con un 'TypeAdapter' personalizzato. –

risposta

4

Cosa ho fatto finalmente sta per il mio progetto API e creare un CustomSerializer

public class CustomDateSerializer extends JsonSerializer<Date> { 

    @Override 
    public void serialize(Date t, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException { 
     SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
     String formattedDate = formatter.format(t); 

     jg.writeString(formattedDate); 
    } 
} 

che restituiscono i campi data formato AAAA-MM-DD e ho annotato con

@JsonSerialize(using = CustomDateSerializer.class) 

nella mia applicazione Android ho creato oggetto GSON come

  Reader reader = new InputStreamReader(content); 

      GsonBuilder gsonBuilder = new GsonBuilder(); 
      gsonBuilder.setDateFormat("yyyy-MM-dd"); 
      Gson gson = gsonBuilder.create(); 
      appels = Arrays.asList(gson.fromJson(reader, Appel[].class)); 
      content.close(); 

e funziona per ora .. grazie per la vostra aiuto lo apprezzo

+0

Dove scrivere questo @JsonSerialize (usando = CustomDateSerializer.class) – KJEjava48

+1

Non è più necessario creare un serializzatore personalizzato.Vedi qui per un esempio: http://stackoverflow.com/a/34187419/1103584 – DiscDev

0

Il valore 1382828400000 è un lungo (tempo in millisecondi). Si sta dicendo GSON che il campo è un Date, e non può convertire automaticamente una long in un Date.

È necessario specificare i campi come valori lunghi

private long dateParution; 
private long heureParution; 
private long dateLimite; 
private long heureLimite; 

e dopo GSON getta la stringa JSON alla desiderata Appel istanza di classe, costruire un altro oggetto con quei campi come date e convertirli mentre assegnando i valori di il nuovo oggetto.

Un'altra alternativa è quello di implementare il proprio Deserializer personalizzato:

public class CustomDateDeserializer extends DateDeserializer { 
    @Override 
    public Date deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException { 
     // get the value from the JSON 
     long timeInMilliseconds = Long.parseLong(jsonParser.getText()); 

     Calendar calendar = Calendar.getInstance(); 
     calendar.setTimeInMillis(timeInMilliseconds); 
     return calendar.getTime(); 
    } 
} 

È necessario impostare questo deserializzatore personalizzati sui vostri campi desiderati, i metodi setter, come:

@JsonDeserialize(using=CustomDateDeserializer.class) 
public void setDateParution(Date dateParution) { 
    this.dateParution = dateParution; 
} 
4

personalizzati Serializzatori non sono più necessari - è sufficiente utilizzare GsonBuilder, e specificare il formato della data, in quanto tale:

Timestamp t = new Timestamp(System.currentTimeMillis()); 

String json = new GsonBuilder() 
       .setDateFormat("yyyy-MM-dd hh:mm:ss.S") 
       .create() 
       .toJson(t); 

System.out.println(json); 
Problemi correlati