好的,上次我问了这个问题,在我删除它之前,它被3个人否决了。可能不是很清楚,对不起是我的错。因此,我正在使用改进来制作api点击量。api返回一个JSON,该JSON的字段数据可以为空。所以JSON可以是这样的。
{
"title": "Product",
"description": "A product from Acme's catalog",
"type": "object"
"data":null
}
当它不是null时,它将如下所示
{
"title": "Product",
"description": "A product from Acme's catalog",
"type": "object"
"data":{"b":"xyz","a":123}
}
现在我为这个对象创建了一个模型类,如下所示
public class A {
@Expose
public String title;
@Expose
public String description;
@Expose
public String type;
@Expose
public Data data =new Data();
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
这是数据模型
public class Data {
public Data(){
this.a=0;
this.b="";
}
@Expose
public double a;
@Expose
public String b="";
public Double getA() {
return a;
}
public void setA(Double a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
}
改进会将JSON转换为A类型的Java对象。现在,我对此A类型的对象所做的下一件事是将其转换为B类型的另一个对象。
为了进行转换,我使用了一个实用程序类。它的描述如下
This utility converts one java object to another java object.
* does not support Inheritance
* Mainly useful for when you have two Class one for Restful call and another for ORM suite
* if you get one object from RESTFUL call and another object to be created to save in ORM then generally we
* create another object and manually put the value by setter and getter
* just keep the same field name in both class and use this utility function to assign value from one to another
* and then use another to save in db. So no more stupid getter setter use, it handles nested class and Collection field .
现在我面临的问题是这个类抛出了一个异常
Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
这是我得到的唯一错误,没有其他错误。堆栈跟踪是干净的,只有这个错误。基本上,对象转换失败了。原因很可能是因为数据字段为空,因为在此之前我没有得到任何这样的错误。
这是我的实用程序类(负责对象转换的那个)中的一部分代码。我传递了两个对象类型,一个是source,另一个是destination。本例中的源是类型A的对象,但第一行导致了我在问题中提到的异常。
// get the class of source object
Class sourceObjectType = sourceObject.getClass();
// get the class of destination object
Class destinationObjectType = destinationObject.getClass();
现在我不确定如何处理这个异常。我尝试创建一个构造函数,使数据不为空,但这不起作用。如果有人能给我提点建议或者帮我一下,那就太好了。谢谢!!
发布于 2015-10-06 18:30:58
您可以先使用一个简单的if检查您的destinationObjectType是否为空:
if(destinationObjectType){
// handle your condition here
}
或者,您可以处理异常:
try{
// get the class of source object
Class sourceObjectType = sourceObject.getClass();
// get the class of destination object
Class destinationObjectType = destinationObject.getClass();
}
catch(NullPointerException e){
// Handle your exception here
}
致以问候!
https://stackoverflow.com/questions/32976790
复制相似问题