2017-08-26 93 views
0

我目前正試圖反序列化,它包含上百個對象具有相同的結構JSON對象,像這樣:反序列化JSON與GSON和改造

「data」: { 
    「1」 { 
     「id」 : 1 
     「name」 : 「sample」 
     }, 
     … 
    「1000」 { 
     「id」 : 1000 
     「name」 : 「sample」 
     } 
} 

我怎麼會去與GSON,改造這樣做的, rxjava?我能想到的唯一方法就是通過做下面這些看起來不切實際的事情。

public class Data { 

    @SerializedName(「1」) 
    private Item _1; 
    … 
    @SerializedName(「1000」) 
    private Item _1000; 

    Item getItem_1() { 
     return _1; 
    } 

    void setItem_1(Item _1) { 
     this._1 = _1; 
    } 
    … 
    Item getItem_1000() { 
     return _1000; 
    } 

    void setItem_1000(Item _1000) { 
     this._1000 = _1000; 
    } 
} 

回答

0

而不是爲"data"一類,用Map<String, Item>。所有的"1" ... "1000"將是地圖鍵,您可以使用它們或只是忽略它們並使用Map.values()

0

你應該改變你的json格式的結構。使用數組(方括號)而不是1000個對象(大括號)。

{ 
「items」: [ 
    { 
    「id」 : 1 
    「name」 : 「sample」 
    }, 
    … 
    { 
    「id」 : 1000 
    「name」 : 「sample」 
    } 
] 
} 

然後你的類將是如下:

class Data{ 
    Item[] items; 

    Item getItem(int position){ 
     return items[position]; 
    } 

} 

class Item{ 
    int id; 
    String name; 
}