如何使用java泛型和google Gson重构我的代码
你好,我有一个丑陋的代码:如何使用java泛型和google Gson重构我的代码,java,android,json,generics,optimization,Java,Android,Json,Generics,Optimization,你好,我有一个丑陋的代码: public static <T> List<T> convertaParaListaCidades(String JSONObject) { List<Cidade> lista = new ArrayList<Cidade>(); Type type = new TypeToken<List<Cidade>>() {}.getType(); Gs
public static <T> List<T> convertaParaListaCidades(String JSONObject) {
List<Cidade> lista = new ArrayList<Cidade>();
Type type = new TypeToken<List<Cidade>>() {}.getType();
Gson gson = new Gson();
try {
Log.i("INFO", "Tentando converter o json.");
lista = gson.fromJson(JSONObject, type);
} catch (JsonSyntaxException e) {
Log.e("JSON Parser", "Erro " + e.toString()
+ " ao converter o json, resultado: " + e.toString());
} catch (IllegalStateException e) {
Log.e("JSON Parser", "Erro " + e.toString()
+ " ao converter o json, resultado: " + e.toString());
} catch (Exception e) {
Log.e("JSON Parser", "Erro " + e.toString()
+ " ao converter o json, resultado: " + e.toString());
}
return (List<T>) lista;
}
这是:
public static <T> List<T> convertaParaListaBairros(String JSONObject) {
List<Bairro> lista = new ArrayList<Bairro>();
Type type = new TypeToken<List<Bairro>>() {}.getType();
...
}
public static <T> List<T> convertaParaListaDeBusca(String JSONObject) {
List<ElementosPesquisados> lista = new ArrayList<ElementosPesquisados>();
Type type = new TypeToken<List<ElementosPesquisados>>() {}.getType();
...
}
这是:
public static <T> List<T> convertaParaListaBairros(String JSONObject) {
List<Bairro> lista = new ArrayList<Bairro>();
Type type = new TypeToken<List<Bairro>>() {}.getType();
...
}
public static <T> List<T> convertaParaListaDeBusca(String JSONObject) {
List<ElementosPesquisados> lista = new ArrayList<ElementosPesquisados>();
Type type = new TypeToken<List<ElementosPesquisados>>() {}.getType();
...
}
那你有什么问题?
我需要将json反序列化到对象,目前我有4个方法可以做同样的事情,只需将对象更改为反序列化json
为什么不使用泛型?
是的,我试过了,但是。。。Gson很好地反序列化了json,但它不是我想要的对象类型Estado、Cidade或Bairro总是LinkedTreeMap,我的代码无法识别这种类型
问题是什么?我怎样才能压缩这段代码,因为他更可靠,更易于维护。4种方法做同样的事情不是一件好事
obs:如果我打电话
Util。可兑换公寓;它总是返回LinkedTreeMap。Check:,可能对您有用。@Ali我用它代替了List lista=new ArrayList;Type Type=newtypetoken{}.getType;我使用了List lista=newarraylist;Type Type=newtypetoken{}.getType;当我使用通用策略时,我总是接收LinkedTreeMap。我能用这张地图做什么?使用foreach来释放他体内的每一个元素?