我是Java和Android的新手,所以请容忍我。我试图创建一个调用wcf服务并将返回结果从JSON转换为Java对象的函数(我将类型作为对象t传递),但它在t上抛出了一个空指针异常,它必须为null,因为我只想传递一个正确类型的对象,以便在转换时填充。请帮帮我。
public static String Post(String serviceURL, Map<String, String> entites,
Class<?> t) {
String responseString = "";
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Gson gson = new GsonBuilder().create();
//now we will try to convert the class to the specified type.
t = (Class<?>) gson.fromJson(responseString, t);
} catch (Exception e) {
responseString = e.toString();
}
return responseString;非常感谢。
经过几次尝试,我最终得到了这段代码,但我仍然面临着空指针异常。
MemberInfo mem = new MemberInfo();
TypeToken<MemberInfo> m = null ;
ServiceCaller.Post(getString(R.string.LoginService), values , m);
Gson gson = new GsonBuilder().create();
//now we will try to convert the class to the specified type.
t = (TypeToken<T>) gson.fromJson(responseString, (Type) t);发布于 2013-10-05 23:53:10
据我所知,这是不可能的。为了做到这一点,gson必须能够仅从序列化的字符串中检测到正确的类。但是,可以用许多有效的方式解释单个字符串。例如,在gson网站上举个例子:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
BagOfPrimitives() {
// no-args constructor
}
}在此类的实例上使用Gson.toJson会产生以下字符串:
{"value1":1,"value2":"abc"}但是,如果我让另一个类在所有方面都与第一个类相同,除了名称:
class SackOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
SackOfPrimitives() {
// no-args constructor
}
}然后,这也将被序列化为相同的字符串:
{"value1":1,"value2":"abc"}我的观点是,给定一个像{"value1":1,"value2":"abc"}这样的字符串,gson无法确定是否应该将其反序列化为BagOfPrimitives类型的对象或SackOfPrimitives类型的对象。因此,您必须始终为gson提供正确的类型,因为gson不可能自己找出它。
https://stackoverflow.com/questions/15692612
复制相似问题