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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值