2016-08-03 38 views
1

我有这样的JSON:GSON自定义字段Retrofit2解析 - Android电子

Class MyObject { 
    @SerializedName("attributes") 
    Attribues attributes; 
    @SerializedName("first") 
    String first; 
    @SerializedName("second") 
    String second; 
    @SerializedName("third") 
    String third; 
} 

而且

Class Attributes { 
    @SerializedName("date") 
    String date; 
} 

{ 
    "attributes": { 
     "date": "2016-01-01" 
    }, 
    "first": "05:33", 
    "second": "05:50", 
    "third": "07:22" 
} 

通常我们使用GSON改造解析器做这样的事情来解析此JSON

但我想要做的是:

Class MyObject { 
    // I want date to be here and ignoring the attributes key <--- 
    String date; 
    @SerializedName("first") 
    String first; 
    @SerializedName("second") 
    String second; 
    @SerializedName("third") 
    String third; 
} 

我们该怎么做?约GSON问题

+0

我认为你应该做自定义转换器。看看这个答案 - http://stackoverflow.com/questions/35502079/custom-converter-for-retrofit-2 – Divers

+0

但我使用一个名为retrofit的android库,他们使用他们的转换器,如果它可以在一种方式,我使用他们的转换器,并使其作为第二种解决方案。 – MBH

+1

是的,我给你的链接正是关于retrofit2自定义json转换器 – Divers

回答

2

90%具有相同的答案:使用custom TypeAdapter

+0

所以,如果我的类有10+个字段,只有一个字段有问题,我不能只告诉GSon如何转换该特定的字段,但必须编写一个完整的为我的班级定制适配器?我的类有一个Time字段,其类型在C#中是DateTime,但是在Java中是Date。 Newtonsoft.Json将其序列化为'2016-11-05T14:23:00',但GSon在反序列化对象时为该字段抛出异常(无时区指示符)。 –

+0

只提供您的日期类型适配器 –