gson model for json array without key

别说谁变了你拦得住时间么 提交于 2019-12-11 20:48:05

问题


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?


回答1:


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



回答2:


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();


来源:https://stackoverflow.com/questions/26467136/gson-model-for-json-array-without-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!