Fabian
Fabian

Reputation: 2723

gson model for json array without key

I have the following json from our customer:

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

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

I want to parse the "actions" array as a List< Actions> actionList and the single "action" as Action action.

With

class Action {
  String action;
  boolean yesno;
}

And the childs Array as List< Child> childs with

class Child{
  String id
}

Is that possible without the json keys?

Upvotes: 0

Views: 2591

Answers (2)

Fabian
Fabian

Reputation: 2723

I solved it my self with a custom deserializer. Thanks to dzsonni for the hint.

In the Gson root class:

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

the action class

class Action {
  String action;
  boolean yesno;
}

the deserializer:

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;
    }
}

then just add it to your gson

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

Upvotes: 1

IAmGroot
IAmGroot

Reputation: 13855

Edit:

Your action class is ok, i mis-read slightly.

Add a complete class:

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

actions will be parsed as a paramtere inside, as will childs. Then you need to create a Customers class too, which is part of this. (or exclude it, and GSON will ignore it)

This will populate the ints into childs and Actions into actions.

If indeed, childs is alphanumeric, then just change it to String.

You can then access it via,

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

Upvotes: 1

Related Questions