使用Gson反序列化具有通用对象类型的嵌套JSON

时间:2013-12-17 06:33:54

标签: java android json gson

我目前正在为我的Android应用程序使用基本JSON lib来提取从我们的服务器发送的JSON。为了提高性能,我想搬到Gson。

目前我因为以下原因而无法进行反序列化 -

我的班级 -

public class GameResponse {

    public boolean failed = false;
    public Object jsonObject; // Type cast this object based on the class type passed in json string
}

public class GameBatchResponse {

    public GameResponse[] gameResponses;
}

反序列化我的jsonresponse -

 Gson gson = new Gson();

 GameBatchResponse response = gson.fromJson(jsonResponse, GameBatchResponse.class);

现在,如何告诉Gson需要键入哪个类来强制转换JsonObject。目前它正在将它转换为LinkedTreeMap,因为它不知道它需要键入哪个类来投射它。

当我(MyClass)response.gameResponses[0].jsonObject时,它会给出类强制转换异常。

在当前的实现中,我曾经在我的Json字符串中传递@type,并将使用它来创建MyClass的实例。对于例如 - “@type”:“com.mypackage.MyClass”

我正在寻找相同逻辑的Gson实现,我可以在运行时从JSON字符串中附加的信息告诉Gson类类型

1 个答案:

答案 0 :(得分:0)

尝试这个

public static Object createObjectFromJSON(String jsonString, Map<Class, AbstractAdapter>map,Class classType) {
        GsonBuilder builder = new GsonBuilder();
        if(map!=null) {
            for (Entry<Class, AbstractAdapter> entry : map.entrySet()) {
                builder.registerTypeAdapter(entry.getKey(), entry.getValue());
            }
        }
        builder.setPrettyPrinting();
        builder.serializeNulls();
        Gson  gsonExt = builder.create();
        return gsonExt.fromJson(jsonString, classType);
    }

您必须定义自己的AbstractAdapter类

public class Adapter extends AbstractAdapter{

        @Override
        public AbstractSureCallDataFile deserialize(JsonElement json, Type typeOfT,
                JsonDeserializationContext context) throws JsonParseException  {
            JsonObject jsonObject =  json.getAsJsonObject();
            JsonPrimitive prim = (JsonPrimitive) jsonObject.get(AbstractAdapter.CLASSNAME);
            String className = prim.getAsString();

            Class<?> klass = null;
            try {
                klass = Class.forName(className);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                throw new JsonParseException(e.getMessage());
            }
            return context.deserialize(jsonObject.get(AbstractAdapter.INSTANCE), klass);
        }

        @Override
        public JsonElement serialize(Serializable src, Type typeOfSrc,
                JsonSerializationContext context) {

            JsonObject retValue = new JsonObject();
            String className = src.getClass().getCanonicalName();
            retValue.addProperty(AbstractAdapter.CLASSNAME, className);
            JsonElement elem = context.serialize(src);
            retValue.add(AbstractAdapter.INSTANCE, elem);
            return retValue;
        }

}

并致电

Map<Class, AbstractAdapter> map=new HashMap<>();
                            map.put(Xyz.class, new Adapter());
                            Object obj= createObjectFromJSON(line, map, MainObjectClass.class);
相关问题