我必须使用ajax将数据从视图发送到控制器。下面是我类,我应该将适当的JSON发送到类结构中。Jackson会把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);
}
})发布于 2016-02-05 04:09:33
你把事情搞得太复杂了。不要在最后才使用字符串,否则最终会在json中使用json,这在任何情况下都不太可能有用。
var address = {
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);
}
});发布于 2016-02-05 04:13:33
对象数据上的address成员已被字符串标识。随后的调用会将其视为字符串值(它确实是!)JSON.stringify()可以很好地处理嵌套对象。
https://stackoverflow.com/questions/35210531
复制相似问题