繁体   English   中英

GSON日期序列化JsonSyntaxException

[英]GSON date serialize JsonSyntaxException

我有一个名为DateTime的自定义对象。 我用方法registerTypeAdapter注册TypeAdapter。 我认为GSON会忽略此适配器。 GSON如何在json对象中检测日期? 是否需要在适配器和json中的字符串格式之间建立任何链接?

   builder.registerTypeAdapter(DateTime.class, new JsonDeserializer<DateTime>() 
          {

            public DateTime deserialize(JsonElement arg0, Type arg1,JsonDeserializationContext arg2) throws JsonParseException 
            {
                try{return new DateTime(arg0.getAsString());}
                catch (Exception e){
                    return null;
                    }
            }
});

Json有名称/值对。 几乎可以肯定,您会例外并吃掉它。 您需要提取名称/值对的值以传递到新的DateTime中。 如果您的JSON类似于{“ date”:213424234},那么您需要这样做:

DateTime date = new DateTime(jsonElement.getAsJsonObject().get( "date" ).getAsLong());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM