我在使用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
...
}
我想要的是使用自定义适配器反序列化categoryList。我使用以下代码创建了一个:
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"
}
]
},
...
]
有什么想法吗?
答案 0 :(得分:1)
如果您没有使用annotation
标记Name
字段的JSON
,则您的字段名称应与JSON
字段名称匹配。就像你的java类中的List<Rule> ruleList
列表一样,应该是List<Rule> rules
,因为JSON中的列表名称是rules
。交叉检查所有字段名称。
这只是我的猜测,因为您刚才说您在反序列化方面存在问题,这是一个非常模糊的术语。如果此解决方案不起作用,请通过更新问题发布错误消息。