Java 发送数据以查看时获取 JsonMappingException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22853509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 18:24:06  来源:igfitidea点击:

Getting JsonMappingException while sending data to view

javaajaxjsonspring-mvcHymanson

提问by user3145373 ツ

I am trying to show DB data to my webpage. I have made following code when GET request to the @RequestMapping(value = "/api/binder").

我正在尝试向我的网页显示数据库数据。当 GET 请求到@RequestMapping(value = "/api/binder").

but when get request came to this method it will fetch data (I have print on console and display well) but it doesn't map to my Java Script Ajax call, it's showing me an error.

但是当 get 请求到达此方法时,它将获取数据(我在控制台上打印并显示良好)但它没有映射到我的 Java Script Ajax 调用,它向我显示了一个错误。

Following is my code for to fetch data :

以下是我获取数据的代码:

    @Autowired
    IBinderViewRepository repository;

    @RequestMapping(method= RequestMethod.GET)
    public @ResponseBody
    List<BinderResponse> getBinders(){
        List<BinderView> binders = repository.getBinders();
        List<BinderResponse> responses = new ArrayList<>();
        ModelMapper mapper = Mapper.getInstance();

        for(int i = 0; i < binders.size(); i++){
            System.out.println("In Loop");
            BinderResponse response = mapper.map(binders.get(i),BinderResponse.class);
            System.out.println("Data :: " + response.getBinderName());
            responses.add(response);
        }
        return responses;
    }

but it shows me following error :

但它显示了以下错误:

HTTP Status 500 - Could not write JSON: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]->com.ngl.dto.outgoing.BinderResponse["valid"]); nested exception is com.fasterxml.Hymanson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]->com.ngl.dto.outgoing.BinderResponse["valid"])

Here is ajax call from knockout js :

这是来自淘汰赛 js 的 ajax 调用:

ajax.get('api/binder').done(function(response){ ... }

ajax.get('api/binder').done(function(response){ ... }

Here BinderView and BinderResponsehave same fields :

这里BinderView and BinderResponse有相同的字段:

    private String binderName;
    private String binderAddress1;

and getter setter as well in both. and repository.genBinders()method bring data from DB.

和 getter setter 以及两者。和repository.genBinders()方法从数据库中获取数据。

Here is insert method and works fine for me :

这是插入方法,对我来说很好用:

    @RequestMapping(method= RequestMethod.POST,consumes = "application/json")
    public @ResponseBody
    IWebApiResponse addBinder(@RequestBody AddBinderForm binder){
        .....
    }

Shall I have to put any json annotation on my BinderResponse class ?

我必须把任何 json annotation on my BinderResponse class ?

I don't understand where am i wrong ?Anyone pleas guide me.

我不明白我错在哪里?任何人都请指导我。

UPDATE :

更新 :

public class BinderResponse extends WebApiResponseBase {
    private String binderName;
    private String binderAddress1;

public String getBinderName() {
        return binderName;
    }

    public void setBinderName(String binderName) {
        this.binderName = binderName;
    }

    public String getBinderAddress1() {
        return binderAddress1;
    }

    public void setBinderAddress1(String binderAddress1) {
        this.binderAddress1 = binderAddress1;
    }
}

BinderView :

活页夹视图:

    public class BinderView extends BaseView {
        private String binderName;
        private String binderAddress1;
    public String getBinderName() {
            return binderName;
        }

        public void setBinderName(String binderName) {
            this.binderName = binderName;
        }

        public String getBinderAddress1() {
            return binderAddress1;
        }

        public void setBinderAddress1(String binderAddress1) {
            this.binderAddress1 = binderAddress1;
        }

}

In console it prints data / BinderName :

在控制台中它打印 data / BinderName :

In Loop
Data :: ada
In Loop
Data :: tya

New Update :

新更新:

Here is BaseView:

这是BaseView

@MappedSuperclass
public abstract class BaseView implements IEntity {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    @Column(name="id")
    private long id;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        if (this.id != 0 && this.id != id) {
            throw new IllegalStateException(
                    "The ID must not be changed after it is set.");
        }
        this.id = id;
    }
}

and In IEntity:

IEntity 中

public interface IEntity  extends Serializable {
    long getId();
    void setId(long id);
}

WebApiResponseBase:

WebApiResponseBase

public class WebApiResponseBase implements IWebApiResponse {

    private String _uri;

    @Override
    public String getUri() {
        return _uri == null ? "" : _uri;
    }

    @Override
    public void setUri(String uri) {
        _uri = uri;
    }
}

采纳答案by Sotirios Delimanolis

Hymanson, by default, serializes an object's whole inheritance hierarchy, ie. the parent class fields as well. In the case of

默认情况下,Hymanson 序列化对象的整个继承层次结构,即。父类字段也是如此。如果是

public class BinderResponse extends WebApiResponseBase {

it seems like

这好像是

Could not write JSON: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]->com.ngl.dto.outgoing.BinderResponse["valid"]); nested exception is com.fasterxml.Hymanson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]->com.ngl.dto.outgoing.BinderResponse["valid"])

Hymanson tries to serialize a field called validfrom a gettercalled isValid(which is a conventional bean property name). The getter method, however, seems to throw a NullPointerExceptionfor whatever reason.

Hymanson 尝试序列化validgetter被调用者调用的字段isValid(这是一个传统的 bean 属性名称)。然而,NullPointerException无论出于何种原因,getter 方法似乎都抛出了 a 。

If you want Hymanson to ignore it, you can annotate the getter with @JsonIgnoreor your class with @JsonIgnorePropertiesand specify the property name, ie. valid.

如果你想让Hyman逊忽略它,你可以用@JsonIgnore或你的类注释 getter@JsonIgnoreProperties并指定属性名称,即。valid.

回答by Vinit Bhardwaj

 @Column(name="createddate")  
 private Date createdDate; 

 @Transient
 private String formatedCreatedDate;  


public String getFormatedCreatedDate() {
    DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
    return dateFormat.format(this.getCreatedDate());
}

It throws the same exception because here may be null by calling getCreatedDate() value come so it can't format null date so keep null check here like:

它抛出相同的异常,因为通过调用 getCreatedDate() 值来这里可能为空,因此它无法格式化空日期,因此在此处保持空检查,例如:

Solution

解决方案

public String getFormatedCreatedDate() {
    DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
    Date createDdate=this.getCreatedDate();
    **if(createDdate!=null){
        return  dateFormat.format(createDdate);
    }**
    return "-";
}

回答by Far Zad

In my case when I used @JsonIgnorethe exception has been gone but the problem was it couldn't receive that value from API Requestanymore and Spring ignored it (obviously because of @JsonIgnore) So I investigated about the issue and figured out that the problem was the getterand setter. I had the Integerproperty while my getterwas int. So when I changed the getterto Integermy problem solved and error's gone.

在我的情况下,当我使用@JsonIgnore异常已经消失但问题是它无法再接收该值API Request并且 Spring 忽略了它(显然是因为@JsonIgnore)所以我调查了这个问题并发现问题是getterand setter。我有Integer产权,而我getterint。因此,当我更改getterInteger我的问题解决并且错误消失了。

private Integer purchaseId;

@JsonIgnore
public int getPurchaseId() {
    return purchaseId;
}

public void setPurchaseId(int purchaseId) {
    this.purchaseId = purchaseId;
}

Changed to :

变成 :

private Integer purchaseId;


public Integer getPurchaseId() {
    return purchaseId;
}

public void setPurchaseId(Integer purchaseId) {
    this.purchaseId = purchaseId;
}