Gson: JsonSyntaxException on date

后端 未结 4 675
别那么骄傲
别那么骄傲 2020-12-10 13:08

I am trying to use Gson to deserialize a json array, but am currently getting a JsonSyntaxException. The json string was created by a .NET MVC3 web service using JsonResult

4条回答
  •  失恋的感觉
    2020-12-10 13:30

    Another solution is to use ISO 8601 format. This has to be configured on both Gson side as:

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

    as well as on the server side, e.g. for ASP.NET MVC in Global.asax.cs file, as follows:

    JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
    serializerSettings.Converters.Add(new IsoDateTimeConverter());
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = serializerSettings;
    

    The advantage of the code above is that it handles both serialization and deserialization and thus allows two way transmission of dates/times.

    Note: IsoDateTimeConverter class is part of the JSON.NET library.

提交回复
热议问题