$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[ this.name].push) {
o[this.name] = [ o[this.name] ];
}
o[this.name].push(this.value || '' );
} else {
o[this.name] = this.value || '';
}
});
return o;
}
This function is sufficient for ordinary object conversion, but it cannot be supported if the object contains sub-objects.
For example, I have a form like this:
The domain class corresponding to the server is as follows:
public class DummyProduct {
private DummyCategory category;
private String name;
public DummyCategory getCategory() {
return category;
}
public void setCategory(DummyCategory category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class DummyCategory {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
If you want to serialize form data into a json string that matches the server-side domain class, you can use my following extension
/**@serializedParams looks like "prop1=value1&prop2=value2".
Nested property like 'prop.subprop=value' is also supported **/
function paramString2obj (serializedParams) {
var obj={};
function evalThem (str) {
var attributeName = str.split("=")[0];
var attributeValue = str.split("=")[1];
if(!attributeValue){
return ;
}
var array = attributeName.split(".");
for (var i = 1; i < array.length; i ) {
var tmpArray = Array();
tmpArray.push("obj");
for (var j = 0; j < i; j ) {
tmpArray.push(array[j]);
};
var evalString = tmpArray.join(".");
// alert(evalString);
if(!eval(evalString)){
eval(evalString "={ };");
}
};
eval("obj." attributeName "='" attributeValue "';");
};
var properties = serializedParams .split("&");
for (var i = 0; i < properties.length; i ) {
evalThem(properties[i]);
};
return obj;
}
$.fn.form2json = function(){
var serializedParams = this.serialize();
var obj = paramString2obj(serializedParams);
return JSON.stringify(obj) ;
}
It probably looks like this:
var json = $("#testform").form2json();
alert(json);