1

I am trying to serialize a form into a JSON object in such a way that i can send the data via AJAX. I'm using the function below:

$.fn.serializeObject = function() {
var arrayData, objectData;
arrayData = this.serializeArray();
objectData = {};
$.each(arrayData, function() {
    var value;
    if (this.value != null && this.value != '') {
        value = this.value;
    } else {
        value = null;
    }
    if (objectData[this.name] != null) {
        if (!objectData[this.name].push) {
            objectData[this.name] = [ objectData[this.name] ];
        }

        objectData[this.name].push(value);
    } else {
        objectData[this.name] = value;
    }
});
return objectData;

};

The problem is that my serialization does not take into account cyclic data structures. For example i have in my form

<form:input path="discipline.cnfpDisciplineCode" class="required" />

and this gets serialized as

{
    ...
    discipline.cnfpDisciplineCode : someValue
    ...
}

Is there an elegant solution to serialize the form to make it look like

{
    ...
    discipline : 
        {
            cnfpDisciplineCode : someValue
        }
    ...
}

Or do i have to implement the whole parsing algorithm myself?

Thank you.

Chandu
  • 81,493
  • 19
  • 133
  • 134
Andrei
  • 53
  • 1
  • 5

2 Answers2

0

Not sure if I got what you trying to do, here´s is something I would use in this situation.

First, you can build a function to create an object and send it to the server using jQuery.ajax

$.ajax({
        url: "servletAdress",
        type: "POST",
        accepts: "application/json",
        data: {obj: JSON.stringify(object) }, //it can be an array
        dataType: "json",
        beforeSend: function(x) {
            if (x && x.overrideMimeType) {
                x.overrideMimeType("application/json;charset=UTF-8");
            }
        }
});

Them you will receive the JSON as a String in the servlet addressed in the paramether 'obj'.

You may want to parse this in the servlet using com.google.gson

Or simply take the form and submit it to the servlet.

Carlos Cariello
  • 133
  • 2
  • 8
0

I don't think that there is a ready-to-use function to transform paths like a.b.c into nested objects. Several solutions for the path-setting and -getting problem are presented in the following thread:

Convert JavaScript string in dot notation into an object reference

As you're already using Spring (at least it looks like you are, because of the tag-lib) you could automatically transform input-parameters into an object, if it's that what you wanna do. The idea is that there is an object on the server-side that represents some state, you parse this object into a form as usual, and Spring handles back-transformation from input-parameters to the POJO by itself. Have a look at some examples for Springs @ModelAttribute annotation in this case.

Community
  • 1
  • 1
Storrm
  • 102
  • 1
  • 7