2014-10-20 27 views
0

我從我們的客戶以下JSON:GSON模型,而關鍵

{ 
    "id": 1234, 
    "delivery_date": 1234567890, 

    "actions": [ 
     [ "foo", true], 
     [ "bar", true] 
    ], 
    "customer": { 
     "id": 12345, 
     "company": "", 
     "firstname": "John", 
     "lastname": "Smith", 
     "action": ["dothis", true] 
    }, 
    "childs": [ 123abc2132312312,11232432943493] 
} 

我想分析的「動作」數組列表<操作>的ActionList和單一的「行動」爲行動行動。

隨着

class Action { 
    String action; 
    boolean yesno; 
} 

而且孩子的數組作爲列表<兒童>與

class Child{ 
    String id 
} 

童車這是可能的,而不JSON鑰匙?

+0

是否設置了結構?我沒有看到在動作中有兩個元素數組的背後的任何原因 – dzsonni 2014-10-20 13:53:58

+0

您可以使'List '爲'Action'的參數。它應該相應地填充。如果你想保持它們獨立,那麼從GSON創建另一個類,然後分割它。 – Doomsknight 2014-10-20 13:56:18

+0

是的結構設置。我已經要求將json更改爲鍵值對 - 沒有成功:( – Fabian 2014-10-20 13:56:41

回答

1

我解決了它我自己有一個自定義解串器。感謝dzsonni的提示。

在GSON根類:

private ArrayList<Action> parcel_actions = new ArrayList<Action>(); 

動作類

class Action { 
    String action; 
    boolean yesno; 
} 

解串器:

public class ActionDeserializer implements JsonDeserializer<ArrayList<Action>> { 

    @Override 
    public ArrayList<Action> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 
     ArrayList<Actions> list = new ArrayList<Action>(){}; 

     if(json.getAsJsonArray().get(0).isJsonPrimitive()){ 
      String action = json.getAsJsonArray().get(0).getAsString(); 
      boolean doIt = json.getAsJsonArray().get(1).getAsBoolean(); 
      list.add(new Action(action, doIt)); 
     } 
     else { 
      for(JsonElement element : json.getAsJsonArray()) { 
       String action = element.getAsJsonArray().get(0).getAsString(); 
       boolean doIt = element.getAsJsonArray().get(1).getAsBoolean(); 
       list.add(new Action(action, doIt)); 
      } 
     } 

     return list; 
    } 
} 

然後只需將它添加到您的GSON

GsonBuilder builder = new GsonBuilder(); 
builder.registerTypeAdapter(new TypeToken<ArrayList<Action>>(){}.getType(), new ActionsDeserializer()); 
Gson gson = builder.create(); 
+0

幹得好。看起來很理想。 :) – Doomsknight 2014-10-21 15:08:12

1

編輯:

你的行動類別沒問題,我稍微讀錯了。

添加一個完整的類:

class Delivery { 
    Int32 id; 
    Int32 delivery_date; 
    list<Action> actions; 
    Customer customer; 
    list<Int32> childs; 
} 

行動將被解析爲內部paramtere,如將孩子的。 然後你需要創建一個Customers類,這也是其中的一部分。 (或排除它,並且將GSON忽略)

這將填充int s轉換childsActionsactions

如果確實,childs是字母數字,那麼只需將其更改爲String即可。

然後,您可以通過訪問它,

Delivery delivery = GSON ... etc 
    var x = delivery.actions; // Actions 
    var y = delivery.childs; // Childs 
+1

gson怎麼自動把上面的json解析成這個類?孩子們甚至不是行動的關鍵 – dzsonni 2014-10-20 14:03:35

+0

@dzsonni你的權利,我瀏覽了一個重要的方面。他需要把GSON作爲一個整體。 – Doomsknight 2014-10-20 14:05:14

+0

查看編輯,作爲一個完整的例子 – Doomsknight 2014-10-20 14:12:36