Java com.google.gson.JsonSyntaxException 尝试解析 json 中的日期/时间时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22841306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 18:16:58  来源:igfitidea点击:

com.google.gson.JsonSyntaxException when trying to parse Date/Time in json

javaandroidjsongson

提问by Noureddine

I'm using RestTemplete to get json data from a rest api and I'm using Gson to parse data from json format to Object

我正在使用 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));

but I get this problem with Date, what should I do ..

但是我在 Date 上遇到了这个问题,我该怎么办..

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

my Pojo that contains other pojos in it's body

我的 Pojo 在它的身体中包含其他 pojo

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

this is ths json returned by my API

这是我的 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"
       }
   },
  .....
]

采纳答案by Noureddine

What I've done finally is going to my API project and create a CustomSerializer

我最后所做的是去我的 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);
    }
}

that return the format yyyy-MM-dd and I annotated date fields with

返回格式 yyyy-MM-dd 并且我用

@JsonSerialize(using = CustomDateSerializer.class)

in my Android application I created Gson object as

在我的 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();

and it works for now .. thanks for your help I appreciate it

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

回答by Raul Rene

The 1382828400000value is a long (time in milliseconds). You are telling GSONthat the field is a Date, and it cannot automatically convert a longinto a Date.

1382828400000值很长(时间以毫秒为单位)。您告诉GSON该字段是 a Date,并且它不能自动将 a 转换long为 a Date

You have to specify your fields as long values

您必须将字段指定为长值

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

and after GSONcasts the JSON string to the desired Appelclass instance, construct another object with those fields as Dates and convert them while assigning the values to the new object.

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

Another alternativeis to implement your own Custom Deserializer:

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

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

You have to set this custom deserializer on your desired fields, on the setter methods, like:

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

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

回答by DiscDev

Custom Serializers are no longer necessary - simply use GsonBuilder, and specify the date format, as such:

不再需要自定义序列化程序 - 只需使用 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);