볼 데이터를 보내는 동안 JsonMappingException을 가져오는 중
제 웹 페이지에 DB 데이터를 표시하려고 합니다.GET 요청 시 다음 코드를 작성했습니다.@RequestMapping(value = "/api/binder")
.
그러나 get request가 이 메서드에 오면 데이터를 가져올 것입니다(콘솔에 인쇄되어 있고 잘 표시됩니다). 그러나 Java Script Ajax 호출에 매핑되지 않습니다. 오류가 표시됩니다.
다음은 데이터를 가져오기 위한 내 코드입니다.
@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;
}
하지만 다음과 같은 오류가 표시됩니다.
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.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]->com.ngl.dto.outgoing.BinderResponse["valid"])
다음은 녹아웃 js의 아약스 전화입니다.
ajax.get('api/binder').done(function(response){ ... }
여기서BinderView and BinderResponse
필드가 동일합니다.
private String binderName;
private String binderAddress1;
그리고 두 가지 모두에서 더 나은 세터입니다.repository.genBinders()
메서드가 DB에서 데이터를 가져옵니다.
삽입 방법은 다음과 같습니다.
@RequestMapping(method= RequestMethod.POST,consumes = "application/json")
public @ResponseBody
IWebApiResponse addBinder(@RequestBody AddBinderForm binder){
.....
}
하나라도 넣어야 할까요?json annotation on my BinderResponse class ?
제가 어디가 틀렸는지 모르겠어요?누구든 저를 안내해 주세요.
업데이트:
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;
}
}
바인더 보기:
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;
}
}
콘솔에서 데이터 / BinderName:
In Loop
Data :: ada
In Loop
Data :: tya
새 업데이트:
다음은 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;
}
}
그리고 독립체에서:
public interface IEntity extends Serializable {
long getId();
void setId(long id);
}
WebApi 응답 기반:
public class WebApiResponseBase implements IWebApiResponse {
private String _uri;
@Override
public String getUri() {
return _uri == null ? "" : _uri;
}
@Override
public void setUri(String uri) {
_uri = uri;
}
}
Jackson은 기본적으로 개체의 전체 상속 계층, 즉 상위 클래스 필드를 직렬화합니다.의 경우에는
public class BinderResponse extends WebApiResponseBase {
는 것 같습니다.
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.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]->com.ngl.dto.outgoing.BinderResponse["valid"])
잭슨은 다음과 같은 필드를 연재하려고 합니다.valid
a부터getter
불렀다isValid
(일반적인 콩 속성 이름).하지만, 더 나은 방법은, 그것을 던지는 것처럼 보입니다.NullPointerException
이유야 어떻든
잭슨이 그것을 무시하기를 원한다면, 당신은 Getter에 주석을 달 수 있습니다.@JsonIgnore
또는 당신의 수업과@JsonIgnoreProperties
속성 이름을 지정합니다.valid
.
제 경우에는 사용할 때@JsonIgnore
예외는 사라졌지만 문제는 그 값을 받을 수 없다는 것이었습니다.API Request
더 이상 그리고 스프링은 그것을 무시했습니다 (분명히 그것 때문입니다).@JsonIgnore
) 그래서 저는 그 문제에 대해 조사했고 문제가 있다는 것을 알았습니다.getter
그리고.setter
나는.Integer
내가 있는 동안 재산getter
이었다int
그래서 제가 바꿨을 때.getter
로.Integer
제 문제는 해결되었고 오류는 사라졌습니다.
private Integer purchaseId;
@JsonIgnore
public int getPurchaseId() {
return purchaseId;
}
public void setPurchaseId(int purchaseId) {
this.purchaseId = purchaseId;
}
다음으로 변경:
private Integer purchaseId;
public Integer getPurchaseId() {
return purchaseId;
}
public void setPurchaseId(Integer purchaseId) {
this.purchaseId = purchaseId;
}
@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());
}
여기서 getCreatedDate() 값이 null일 수 있으므로 null 날짜를 형식으로 지정할 수 없으므로 다음과 같이 null 확인을 유지합니다.
해결책
public String getFormatedCreatedDate() {
DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
Date createDdate=this.getCreatedDate();
if(createDdate!=null){
return dateFormat.format(createDdate);
}
return "-";
}
언급URL : https://stackoverflow.com/questions/22853509/getting-jsonmappingexception-while-sending-data-to-view
'it-source' 카테고리의 다른 글
Excel 2010 - 전체 셀이 아닌 하이퍼링크 텍스트만 (0) | 2023.08.29 |
---|---|
다른 모든 항목이 로드될 때까지 jquery 스크립트 지연 (0) | 2023.08.29 |
PowerShell은 어떤 언어입니까? (0) | 2023.08.29 |
전용 생성자가 있는 Java Springbean (0) | 2023.08.29 |
단추를 클릭하여 표 행의 내용 가져오기 (0) | 2023.08.29 |