我必须使用ajax将数据从视图发送到控制器。 这是我的类,我应该发送适合该类结构的JSON。杰克逊将JSON转换为我的班级
public class RealEstateAgencyDTO extends BaseEntityDTO {
/** The name. */
private String name;
/** The description. */
private String description;
/** The site. */
private String site;
/** The phone number. */
private String phone;
/** The address of the office. */
private AddressDTO address;
public final String getName() {
return name;
}
public final void setName(final String newName) {
this.name = newName;
}
public final String getDescription() {
return description;
}
public final void setDescription(final String newDescription) {
this.description = newDescription;
}
public final String getSite() {
return site;
}
public final void setSite(final String newSite) {
this.site = newSite;
}
public final String getPhone() {
return phone;
}
public final void setPhone(final String newPhone) {
this.phone = newPhone;
}
public final AddressDTO getAddress() {
return address;
}
public final void setAddress(final AddressDTO newAddress) {
this.address = newAddress;
}
}
我应该如何使用JSON.stringify()来获得与我的结构相对应的对象
我试过像这样使用smth但它不起作用
var address = JSON.stringify({
country: $('#country').val(),
region: $('#description').val(),
postalCode: $('#postalCode').val(),
locality: $('#locality').val(),
additionalInfo: $('#additionalInfo').val()
});
var data = {
agencyName: $('#agencyName').val(),
description: $('#description').val(),
phoneNumber: $('#phoneNumber').val(),
webSite: $('#webSite').val(),
address: address
};
$.ajax({
type: "post",
url: "registerAgency",
data: JSON.stringify(data),
contentType: "application/json",
success: function(responseData, textStatus, jqXHR) {
alert("data saved")
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
答案 0 :(得分:1)
你过度复杂了。直到最后才进行字符串化,否则你最终会在json中使用json,这在任何情况下都不太可能有用。
PersonAccessToken
答案 1 :(得分:0)
对象数据上的地址成员已经被字符串化。后续调用会将此视为字符串值(它是!)JSON.stringify()将处理嵌套对象。