2016-03-31 31 views
0

這是我建立我的GSON:Gson gson = new GsonBuilder().create();當使用 'fromJson' deserialising對象,GSON使得空數組 '空'

這是我從Json的創建對象:

JsonObject obj = gson.fromJson(line, JsonObject.class); //JsonObject allows us to retrieve information by name 

Class<? extends Tile> resultClass = (Class<? extends Tile>) Class.forName(obj.get("className").getAsString()); //Get the class of the tile we are currently processing 
newTile = resultClass.cast(gson.fromJson(line, resultClass)); //Cast the new tile to the correct class 

我我調試了這段代碼,它似乎工作正常(返回一個與json中的值相同的對象)。但是,當我試圖訪問對象超超類中的空數組(該數組未在json中列出)時,該數組爲'null'。該陣列發起這樣的:

private ArrayList<Entity> elements = new ArrayList<Entity>();

所以每次的對象被創建以正常的方式,陣列開始,但GSON創建時,該數組爲null。

Gson沒有初始化空數組嗎?我是否必須在Json中包含空數組以便初始化它?

+0

可能的重複項:http://stackoverflow.com/q/11407541/2920722 – bszeliga

回答

0

如果Gson遇到一個在json文件中沒有字段的變量,它會自動設置爲null,而不是默認值。 Source

我想我只需要將每個變量保存到一個字段,或者手動創建對象並手動應用相關字段。