将JSON字符串转换为JAVA中的通用对象(使用GSON) [英] Convert JSON String to generic object in JAVA (with GSON)

查看:796
本文介绍了将JSON字符串转换为JAVA中的通用对象(使用GSON)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回JSON的Api。响应采用某种格式,可以放入名为ApiResult的对象中,并且包含 Context< T> 和一个int代码。

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 <T> and an int Code.

ApiResult以通用方式声明,例如 ApiResult< SomeObject>

ApiResult is declared in a generic way, e.g. ApiResult<SomeObject>

我想知道如何让GSON将传入的JSON字符串转换为 ApiResult< T>

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

到目前为止,我有:

So far I have:

Type apiResultType = new TypeToken<ApiResult<T>>() { }.getType();
ApiResult<T> result = gson.fromJson(json, apiResultType);

但是,这仍然返回将上下文转换为LinkedHashMap(我认为它是GSON回退到)

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

推荐答案

你必须知道T将会是什么。传入的JSON基本上只是文本。 GSON不知道你希望它成为什么样的对象。如果在JSON中有某些东西可以用来创建T实例,那么可以这样做:

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<X> implements JsonDeserializer<ApiResult<X>>
{
    public ApiResult<X> 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 );
      }
    }
}

我正在使用字段_class来决定我需要的X,并通过反射来实例化它(类似于PomPom的例子)。你可能没有这样一个明显的领域,但是你必须有一些方法让你看看JsonElement,并根据它是什么类型来决定它应该是什么类型的。

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.

这段代码是我之前用GSON做过的类似黑客攻击的版本,请参见第184+行: https://github.com/chriskessel/MyHex/blob/master/src/kessel/hex/domain/GameItem.java

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

这篇关于将JSON字符串转换为JAVA中的通用对象(使用GSON)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆