Reputation: 16561
my data:
var test = {cars : []};
var cars = []
cars.push({
"name" : "Ford",
"year" : "2000"
});
cars.push({
"name" : "Audi",
"year" : "2002"
});
test.cars = cars;
var json = JSON.stringify(test);
$.get('/myservlet/', json, function(data) { // also tried .getJSON , .post
alert('Success');
})
In Java I get the "json" variable as parameter key, but no value.
public void doPost(...) // TRIED BOTH
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
for(Object a : req.getParameterMap().keySet()) {
System.out.println(a + " - " + req.getParameter((String)a));
}
//prints out
{"cars":[{"name":"Ford","year":"30"},{"name":"Audi","year":"2002"}]} -
This is unusable result, because the key is always changing, and is ridiculous to for-loop the params everytime. I need to have a specific key : req.getParameter("cars")
Upvotes: 2
Views: 3017
Reputation: 1109655
You shouldn't have stringified the JSON at all. The whole JSON object test
is supposed to be treated as the request parameter map. Just pass the JSON object unmodified.
$.get('/myservlet/', test, function(data) {
// ...
});
This way it's available in the servlet as follows:
for (int i = 0; i < Integer.MAX_VALUE; i++) {
String name = request.getParameter("cars[" + i + "][name]");
if (name == null) break;
String year = request.getParameter("cars[" + i + "][year]");
// ...
}
Upvotes: 0
Reputation: 4197
Update Your question could be possible duplicate of READ JSON String in servlet
Previous answer
I assume you are trying to post JSON to the servlet, if thats the case read on.
You would have to check for request body instead of request parameter. Something like
BufferedReader buff = req.getReader();
Check if this works for you
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
BufferedReader buff = req.getReader();
char[] buf = new char[4 * 1024]; // 4 KB char buffer
int len;
while ((len = reader.read(buf, 0, buf.length)) != -1) {
out.write(buf, 0, len);
}
}
Note that I have checked the above code for syntax errors. I hope you get the idea.
Upvotes: -1
Reputation: 953
Change it to:
$.get('/myservlet/', 'cars='+ json, function(data) { // also tried .getJSON , .post
alert('Success');
Upvotes: 2