Bootstrap

idea json转为对象_将JSON字符串转换为JAVA中的通用对象(使用GSON)

I have an Api that returns JSON. The response is in some format that can fit into an object called ApiResult and contains a Context and an int Code.

ApiResult is declared in a generic way, e.g. ApiResult

I would like to know how to get GSON to convert the incoming JSON String to ApiResult

So far I have:

Type apiResultType = new TypeToken>() { }.getType();

ApiResult result = gson.fromJson(json, apiResultType);

But this still returns converts the Context to a LinkedHashMap instead (which I assume its what GSON falls back to)

解决方案

You have to know what T is going to be. The incoming JSON is fundamentally just text. GSON has no idea what object you want it to become. If there's something in that JSON that you can clue off of to create your T instance, you can do something like this:

public static class MyJsonAdapter implements JsonDeserializer>

{

public ApiResult deserialize( JsonElement jsonElement, Type type, JsonDeserializationContext context )

throws JsonParseException

{

String className = jsonElement.getAsJsonObject().get( "_class" ).getAsString();

try

{

X myThing = context.deserialize( jsonElement, Class.forName( className ) );

return new ApiResult<>(myThing);

}

catch ( ClassNotFoundException e )

{

throw new RuntimeException( e );

}

}

}

I'm using a field "_class" to decide what my X needs to be and instantiating it via reflection (similar to PomPom's example). You probably don't have such an obvious field, but there has to be some way for you to look at the JsonElement and decide based on what's itn it what type of X it should be.

This code is a hacked version of something similar I did with GSON a while back, see line 184+ at: https://github.com/chriskessel/MyHex/blob/master/src/kessel/hex/domain/GameItem.java

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;