2013-12-17 41 views
0

我目前正在爲我的android應用程序使用基本的JSON庫來提取從我們的服務器發送的JSON。爲了提高性能,我正在考慮轉向Gson。使用Gson反序列化具有通用對象類型的嵌套JSON

目前我因爲以下原因,我堅持與deserialzation -

我的班 -

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類的類型

+0

爲了幫助你,最好有一個你試圖反序列化的JSON的例子。 – giampaolo

回答

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); 
+0

沒有AbstractAdapter – gfan

相關問題