1
我在使用gson反序列化自定義對象時遇到了問題。 我有這個類:改裝:GSON兒童自定義反序列化列表
public class Content implements java.io.Serializable {
private Long id;
private int tipo;
private String title;
private String content;
private Integer reward;
/** Not-null value. */
private String imageUrl;
private String bannerUrl;
private String logoUrl;
/** Not-null value. */
private String actionUrl;
private Integer templateType;
private String expiresAt;
private Integer unlockReward;
private Integer reportType;
private String completionType;
private Integer interactionType;
private Integer productId;
private Integer views;
private Boolean saved;
private Double weight;
/** Used to resolve relations */
private transient DaoSession daoSession;
/** Used for active entity operations. */
private transient ContentDao myDao;
private List<Rule> ruleList;
private List<Category> categoryList;
...
// all getters and setters code
...
}
我想是反序列化使用自定義適配器所屬分類。我用下面的代碼創建一個:
Type typeOfListOfCategory = new com.google.gson.reflect.TypeToken<List<Category>>(){}.getType();
builder.registerTypeAdapter(typeOfListOfCategory, new JsonDeserializer<List<Category>>() {
@Override
public List<Category> deserialize(JsonElement element, Type type,
JsonDeserializationContext context) throws JsonParseException {
// my code goes in here
}
});
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
然後,我用它休息適配器
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://localhost/api")
.setConverter(new GsonConverter(gson)).build();
上,但我的自定義適配器不會被調用。
,我收到的JSON是這樣的:
[
{
"id": 1,
"tipo": 1,
"title": "title",
"content": "content",
"reward": 2.0,
"image_url": "url1",
"banner_url": "url2",
"logo_url": "url3",
"action_url": "url4",
"template_type": 0,
"expires_at": "2014-08-31T00:00:00.000Z",
"unlock_reward": 2,
"report_type": 0,
"completion_type": 0,
"rules": [
{
"range": "1",
"operator": "==",
"key": "key1"
}
],
"categories": [
{
"description": "description"
}
]
},
...
]
任何想法?
謝謝。你對ruleList和categoryList是正確的。給出FieldNamingPolicy :)其他字段(如actionUrl)都可以。我會盡快接受你的回答。 – gfhuertac 2014-09-24 14:17:41
超過一半的字段被錯誤地命名。對於JSON轉換器,Java中的命名約定發生了變化。字段應該全部用小寫字母和下劃線作爲分隔符。 – Jimmy 2014-09-24 14:19:39
正如我在之前的評論中所說的,只有列表字段被錯誤地命名。給定命名策略(將字段自動轉換爲Java標準)其餘都是正確的。 – gfhuertac 2014-09-24 14:24:28