2014-09-24 103 views
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" 
      } 
     ] 
    }, 
    ... 
] 

任何想法?

回答

1

如果您不使用annotation来标记JSON字段的Name,那么您的字段名称应与JSON字段名称匹配。因为JSON中的列表名称是rules,所以在您的java类中应该使用List<Rule> ruleList列表,因为它应该是List<Rule> rules。交叉检查所有字段名称。

这只是我的猜测,因为你只是说你在反序列化中存在问题,这是非常非常模糊的术语。如果此解决方案无效,请通过更新您的问题发布错误消息。

+0

谢谢。你对ruleList和categoryList是正确的。给出FieldNamingPolicy :)其他字段(如actionUrl)都可以。我会尽快接受你的回答。 – gfhuertac 2014-09-24 14:17:41

+0

超过一半的字段被错误地命名。对于JSON转换器,Java中的命名约定发生了变化。字段应该全部用小写字母和下划线作为分隔符。 – Jimmy 2014-09-24 14:19:39

+0

正如我在之前的评论中所说的,只有列表字段被错误地命名。给定命名策略(将字段自动转换为Java标准)其余都是正确的。 – gfhuertac 2014-09-24 14:24:28