问题 尝试在json中解析日期/时间时com.google.gson.JsonSyntaxException


我正在使用RestTemplete从rest api获取json数据,而我正在使用Gson将数据从json格式解析为Object

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));

但我用Date得到了这个问题,我该怎么办..

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

我的Pojo包含其他pojos的身体

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;
    }

这是我的API返回的json

[
   {
       "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"
       }
   },
  .....
]

5754
2018-04-03 14:51


起源

你的json是什么样的?你的pojo是什么样的? - Sotirios Delimanolis
你正试图投入很长的日期。 - rpax
那些价值观, 1384732800000,好像是时间戳。 Gson未设置为使用时间戳解析日期。您必须使用自定义配置它 TypeAdapter。 - Sotirios Delimanolis
您需要使用GsonBuilder并传递日期格式化程序字符串,以便Gson知道如何解析您的日期。这是一个例子: stackoverflow.com/a/34187419/1103584 - DiscDev


答案:


不再需要自定义序列化程序 - 只需使用GsonBuilder,并指定日期格式,如下所示:

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);

5
2017-12-09 19:30





我最终做的是进入我的API项目并创建一个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);
    }
}

返回格式yyyy-MM-dd和我带注释的日期字段

@JsonSerialize(using = CustomDateSerializer.class)

在我的Android应用程序中,我创建了Gson对象

            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();

它现在有效..感谢您的帮助,我很感激


5
2018-04-04 11:01



在哪里写这个@JsonSerialize(using = CustomDateSerializer.class) - KJEjava48
不再需要创建自定义序列化程序。请看这里的例子: stackoverflow.com/a/34187419/1103584 - DiscDev


1382828400000 value是一个很长的时间(以毫秒为单位)。你在说 GSON 该领域是一个 Date,它不能自动转换 long 变成一个 Date

您必须将字段指定为长值

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

之后 GSON 将JSON字符串转换为所需的字符串 Appel 类实例,构造另一个对象,将这些字段作为日期,并在将值分配给新对象时转换它们。

另一种选择 是实现自己的自定义反序列化器:

 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();
     }
 }

您必须在setter方法上的所需字段上设置此自定义反序列化器,例如:

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

0
2018-04-04 08:46