[英]Is it possible to deserialize JSON property names with periods as a nested object using GSON?
[英]Using Gson to deserialize nested JSON having generic object type
我目前正在為我的android應用程序使用基本的JSON庫,以提取從我們的服務器發送的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
它給出了類(MyClass)response.gameResponses[0].jsonObject
異常。
在當前的實現中,我曾經在Json字符串中傳遞@type,並將使用它來創建MyClass實例。 例如-“ @type”:“ com.mypackage.MyClass”
我正在尋找具有相同邏輯的Gson實現,在這里我可以在運行時從JSON字符串中附加的信息中告訴Gson類類型
試試這個
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.