2017-05-29 48 views
0

我有类还原序列化Date对象JSON

class A { 
    B b; 
} 

class B { 
    @CustomDateFormat(
     format = "yyyy-MM-dd" 
    ) 
    protected Date creationDate; 
} 

接下来的结构我想顺便连载类A的一个实例的JSON输出JSON具有使用注释@CustomDateFormat中的值格式化的creationDate字段。可能吗?理想情况下使用Gson。这将在Android上执行,所以没有Java 8具有ATM功能。

在此先感谢您的任何想法

回答

0

最后,我使用的反射,通过对象的树去和创建的关系日期 - >字符串(格式)。然后创建一个自定义序列化器,并使用提到的地图来相应地设置日期。虽然感谢您的答案!

0

如果@CustomDataFormat值是恒定的,那么你可以使用下面的代码

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

如果那么我认为你必须去思考阅读它不是常数注释值,然后应用于上述代码。

+0

确实不是恒定的。然而,使用反射也不是微不足道的,因为我不知道究竟哪一个Date成员被序列化了。 新JsonSerializer (){ @覆盖 公共JsonElement连载(日期SRC,类型typeOfSrc,JsonSerializationContext上下文){// 在大多数情况下使用YYYY-MM-DD,因此把它作为备用 日期格式字符串=“yyyy-MM-dd”; } } – hhg

+0

换句话说......我将不得不使用Fields作为成员来构建一个类。这会让我回注释。最后用一个自定义的JsonSerializer 编排这些内容。它看起来对我诉哈克,但没有更好的主意 – hhg

0

这可能吗?

的排序。不幸的是,Gson几乎不支持自定义注释。但是,Gson对其@JsonAdapter注释进行本地支持,以便您可以模拟自定义注释。

比方说,

final class A { 

    final B b; 

    A(final B b) { 
     this.b = b; 
    } 

} 
final class B { 

    // Here comes an emulation for @CustomDateFormat(format = "yyyy-MM-dd") 
    @JsonAdapter(YyyyMmDdDateTypeAdapter.class) 
    final Date creationDate; 

    B(final Date creationDate) { 
     this.creationDate = creationDate; 
    } 

} 
abstract class AbstractDateTypeAdapter 
     extends TypeAdapter<Date> { 

    protected abstract DateFormat getDateFormat(); 

    @Override 
    @SuppressWarnings("resource") 
    public final void write(final JsonWriter out, final Date value) 
      throws IOException { 
     out.value(getDateFormat().format(value)); 
    } 

    @Override 
    public final Date read(final JsonReader in) { 
     throw new UnsupportedOperationException("Not implemented"); 
    } 

} 
final class YyyyMmDdDateTypeAdapter 
     extends AbstractDateTypeAdapter { 

    // Let Gson do it itself when needed 
    private YyyyMmDdDateTypeAdapter() { 
    } 

    @Override 
    protected DateFormat getDateFormat() { 
     // SimpleDateFormat is known to be thread-unsafe so it has to be created everytime it's necessary 
     // Maybe Joda Time is an option for you? 
     // Joda Time date formatters are thread-safe and can be safely instantiated once per application 
     return new SimpleDateFormat("yyyy-MM-dd"); 
    } 

} 

例子:

private static final Gson gson = new Gson(); 

public static void main(final String... args) { 
    final A a = new A(new B(new Date())); 
    final String json = gson.toJson(a); 
    System.out.println(json); 
} 

输出:

{ “B”:{ “creationDate”: “2017年5月29日”}}