2

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?

Egor Neliuba
  • 14,784
  • 7
  • 59
  • 77
Po DW
  • 103
  • 1
  • 9

1 Answers1

2
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());
Egor Neliuba
  • 14,784
  • 7
  • 59
  • 77
  • Good answer, but [the documenation](https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonDeserializer.html) says "New applications should prefer `TypeAdapter`, whose streaming API is more efficient than this interface's tree API." – durron597 Apr 27 '15 at 14:28