I am sendng json data to another jsp page – for testing really.
You enter a JSON formatted string in a text field on my jsp from. I submit this through a form request, handled by jquery processing. It is sent to a receiver JSP. I am using the following code to do this.
Before I send it I get the data using:
jsonData = $form.find( 'textarea[name="jsonData"]' ).val();
I then do:
var parsedJsonObject = $.parseJSON(jsonData);
This is my send code:
$.ajax({
type: "POST",
url: "receiver.jsp",
data: "jsonData=" + parsedJsonObject, // This is an object, created using parseJSON
success: function(data, textStatus, jqXHR) {
alert('Success : ' + data);
alert('textStatus : ' + textStatus);
alert('jqXHR : ' + jqXHR);
var jsonJqXHR = JSON.stringify(jqXHR);
alert('jsonJqXHR : ' + jsonJqXHR);
},
error:function (xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
},
//complete: alert('complete'),
dataType: "text" // xml, json, script, text, html
});
In my JSP, I do a:
String jsonData = request.getParameter("jsonData");
System.out.println("jsonData : " + jsonData);
This returns a output of: json : “[object Object]”
How do I deserialize it? I have done some things with gson, but when I have tried:
Gson gson = new Gson();
String json = gson.toJson(obj);
System.out.println("json = " + json); // I still get an output of: json = "[object Object]"
gson.fromJson(json, MyClass.class);
I get an error:
servlet jsp threw exception: com.google.gson.JsonParseException: Expecting object found: "[object Object]"
Can anyone help please on the way I need to get this data out of the object?
In your AJAX call,
data: "jsonData=" + parsedJsonObjectdoesn’t do what you intend:It just gives you a string like
[object Object], not the JSON representation you’re looking for.Use
data: "jsonData=" + JSON.stringify(parsedJsonObject)or some jQuery equivalent.