简体   繁体   中英

How to convert dynamic JSON reponse with Java Gson library

I have an API that can return JSON arrays or objects. Example JSON object

{
  "id": 1,
  "name": "name"
}

JSON array:

[
   {
       "id": 1,
       "name": "name"
   },
   {
       "id": 1,
       "name": "name"
   }
]

When mapping a JSON object response to a POJO I use:

MyEntity myEntity = new Gson().fromJson(jsonString, MyEntity.class);

When mapping a JSON array response to an array of POJOs I use:

MyEntity[] myEntity = new GSON().fromJson(jsonString, MyEntity[].class);

How can I convert those two responses to the appropriate types dynamically?

NOTE: I can't modify the server response, this is a public API.

Thank you!

EDIT:

I am trying to implement a method that does this automatically but I am missing something. The method

public <T> T convertResponseToEntity(Class<T> classOfT)
{
    JsonElement jsonElement =  this.gson.fromJson(getResponseAsString(), JsonElement.class);

    if (jsonElement.isJsonArray()) {
       Type listType = new TypeToken<T>(){}.getType();
       return this.gson.fromJson(getResponseAsString(), listType);
    }

    return this.gson.fromJson(getResponseAsString(), (Type) classOfT);
}

It returns a list of LinkedTreeMap s. How can I modify the code to return the same content as Object[] ?

Just parse it into JsonElement and check actual element type:

Gson g = new Gson();
JsonParser parser = new JsonParser();
JsonElement e = parser.parse( new StringReader(jsonString) );
if(e instanceof JsonObject) {
    MyEntity myEntity = g.fromJson(e, MyEntity.class);
} else {
    MyEntity[] myEntity =  g.fromJson(e, MyEntity[].class);
}

How can I convert those 2 responses dynamically to the appropriate type?

It depends on how to interpret the "appropriate type" here because it would lead to instanceof or visitor pattern to get the appropriate type once you try to handle the parsed-from-JSON object every time you need it. If you can't change the API, you can smooth the way you use it. One of possible options here is handling such response as if everything is a list. Even a single object can be handled as a list with one element only (and many libraries work with sequences/lists only having that fact: Stream API in Java, LINQ in .NET, jQuery in JavaScript, etc).

Suppose you have the following MyEntity class to handle the elements obtained from the API you need:

// For the testing purposes, package-visible final fields are perfect
// Gson can deal with final fields too
final class MyEntity {

    final int id = Integer.valueOf(0); // not letting javac to inline 0 since it's primitive
    final String name = null;

    @Override
    public String toString() {
        return id + "=>" + name;
    }

}

Next, let's create a type adapter that will always align "true" lists and single objects as if it were a list:

final class AlwaysListTypeAdapter<T>
        extends TypeAdapter<List<T>> {

    private final TypeAdapter<T> elementTypeAdapter;

    private AlwaysListTypeAdapter(final TypeAdapter<T> elementTypeAdapter) {
        this.elementTypeAdapter = elementTypeAdapter;
    }

    static <T> TypeAdapter<List<T>> getAlwaysListTypeAdapter(final TypeAdapter<T> elementTypeAdapter) {
        return new AlwaysListTypeAdapter<>(elementTypeAdapter);
    }

    @Override
    @SuppressWarnings("resource")
    public void write(final JsonWriter out, final List<T> list)
            throws IOException {
        if ( list == null ) {
            out.nullValue();
        } else {
            switch ( list.size() ) {
            case 0:
                out.beginArray();
                out.endArray();
                break;
            case 1:
                elementTypeAdapter.write(out, list.iterator().next());
                break;
            default:
                out.beginArray();
                for ( final T element : list ) {
                    elementTypeAdapter.write(out, element);
                }
                out.endArray();
                break;
            }
        }
    }

    @Override
    public List<T> read(final JsonReader in)
            throws IOException {
        final JsonToken token = in.peek();
        switch ( token ) {
        case BEGIN_ARRAY:
            final List<T> list = new ArrayList<>();
            in.beginArray();
            while ( in.peek() != END_ARRAY ) {
                list.add(elementTypeAdapter.read(in));
            }
            in.endArray();
            return unmodifiableList(list);
        case BEGIN_OBJECT:
            return singletonList(elementTypeAdapter.read(in));
        case NULL:
            return null;
        case END_ARRAY:
        case END_OBJECT:
        case NAME:
        case STRING:
        case NUMBER:
        case BOOLEAN:
        case END_DOCUMENT:
            throw new MalformedJsonException("Unexpected token: " + token);
        default:
            // A guard case: what if Gson would add another token someday?
            throw new AssertionError("Must never happen: " + token);
        }
    }

}

Gson TypeAdapter are designed to work in streaming fashion thus they are cheap from the efficiency perspective, but not that easy in implementation. The write() method above is implemented just for the sake of not putting throw new UnsupportedOperationException(); there (I'm assuming you only read that API, but don't know if that API might consume "either element or a list" modification requests). Now it's necessary to create a type adapter factory to let Gson pick up the right type adapter for every particular type:

final class AlwaysListTypeAdapterFactory
        implements TypeAdapterFactory {

    private static final TypeAdapterFactory alwaysListTypeAdapterFactory = new AlwaysListTypeAdapterFactory();

    private AlwaysListTypeAdapterFactory() {
    }

    static TypeAdapterFactory getAlwaysListTypeAdapterFactory() {
        return alwaysListTypeAdapterFactory;
    }

    @Override
    public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken)
            throws IllegalArgumentException {
        if ( List.class.isAssignableFrom(typeToken.getRawType()) ) {
            final Type elementType = getElementType(typeToken);
            // Class<T> instances can be compared with ==
            final TypeAdapter<?> elementTypeAdapter = elementType == MyEntity.class ? gson.getAdapter(MyEntity.class) : null;
            // Found supported element type adapter?
            if ( elementTypeAdapter != null ) {
                @SuppressWarnings("unchecked")
                final TypeAdapter<T> castTypeAdapter = (TypeAdapter<T>) getAlwaysListTypeAdapter(elementTypeAdapter);
                return castTypeAdapter;
            }
        }
        // Not a type that can be handled? Let Gson pick a more appropriate one itself
        return null;
    }

    // Attempt to detect the list element type  
    private static Type getElementType(final TypeToken<?> typeToken) {
        final Type listType = typeToken.getType();
        return listType instanceof ParameterizedType
                ? ((ParameterizedType) listType).getActualTypeArguments()[0]
                : Object.class;
    }

}

And how it's used after all:

private static final Type responseItemListType = new TypeToken<List<MyEntity>>() {
}.getType();

private static final Gson gson = new GsonBuilder()
        .registerTypeAdapterFactory(getAlwaysListTypeAdapterFactory())
        .create();

public static void main(final String... args) {
    test("");
    test("{\"id\":1,\"name\":\"name\"}");
    test("[{\"id\":1,\"name\":\"name\"},{\"id\":1,\"name\":\"name\"}]");
    test("[]");
}

private static void test(final String incomingJson) {
    final List<MyEntity> list = gson.fromJson(incomingJson, responseItemListType);
    System.out.print("LIST=");
    System.out.println(list);
    System.out.print("JSON=");
    gson.toJson(list, responseItemListType, System.out); // no need to create an intermediate string, let it just stream
    System.out.println();
    System.out.println("-----------------------------------");
}

The output:

LIST=null
JSON=null
-----------------------------------
LIST=[1=>name]
JSON={"id":1,"name":"name"}
-----------------------------------
LIST=[1=>name, 1=>name]
JSON=[{"id":1,"name":"name"},{"id":1,"name":"name"}]
-----------------------------------
LIST=[]
JSON=[]
-----------------------------------

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM