Po DW
Po DW

Reputation: 103

GSON to parse JSON having different type data under same name

Hi I'm having the following json data

{
  "actionslist": [
    {
      "type": "SET_TP_DST",
      "port": 135
    },
    {
      "type": "OUTPUT",
      "port": {
        "node": {
          "id": "00:00:00:00:00:00:00:03",
          "type": "OF"
        },
        "id": "2",
        "type": "OF"
      }
    }
  ]
}

I want to deserialize this json using gson.fromJson. But the problem here is the port sometimes holds a number and sometimes holds an object. How can I get the port to get both object and the number?

Upvotes: 2

Views: 534

Answers (1)

Egor Neliuba
Egor Neliuba

Reputation: 15064

public class PortConverter implements JsonDeserializer<Port> {
    public Port deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
        Port port = null;
        if (json.isJsonPrimitive()) {
            // handle your first case:
            port = new Port(json.getAsInt());
            // in this case you will have a Port object with populated id
        } else if (json.isJsonObject()) {
            // manually parse your Port object
            port = new Port();
            port.setNode(ctx.deserialize(json.getAsJsonObject().get("node"), Node.class));
            port.setId(json.getAsJsonObject().get("id").getAsInt());
            port.setType(json.getAsJsonObject().get("type").getAsString());
        }
        return port;
    }
}

POJO classes:

class Port {
    int id;
    String type;
    Node node;

    Port() { }

    Port(int id) { this.id = id; }

    /* setters */

    class Node {
        String id;
        String type;
    }
}

class Action {
    String type;
    Port port;
}

Register your deserializer:

gsonBuilder.registerTypeAdapter(Port.class, new PortConverter());

Upvotes: 2

Related Questions