2016-02-04 194 views
0

我必须使用ajax将数据从视图发送到控制器。 这是我的课程,我应该发送适合该课程结构的JSON。杰克逊将JSON转换成我的课JSON stringify嵌套对象

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(),以获得对应我的结构

我试图使用不便这样一个对象像那样但它不起作用

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); 
        } 
       }) 

回答

1

你太过复杂了。不要直到最后结束,否则你会以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); 
    } 
}); 
0

对象数据的地址成员已被字符串化。随后的调用将把它当作一个字符串值(它是!)JSON.stringify()将处理嵌套对象。