2014-09-24 168 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