问题
this is my javascript code to send json object to servlet
username = "Nash";
password = "619here";
type = "all";
data = '{ "username": "' + username + '", "password": "' + password + '", "type": "' + type + '" }';
request = JSON.parse(data);
$.getJSON(url, request, function (response) {
$("#result").append("<h1>Success</h1>");
$.each(response.vehicle, function (no, vehicle) {
$.each(vehicle, function (key, value) {
$("#result").append("<h2>" + key + " : " + value + "</h2>");
});
$("#result").append("<br>");
});
})
I want read json object from java servlet and get data separately. like this
String username = username from json object
String password = password from json object
String type = type from json object
I'm using json-lib-2.4-jdk15.jar please help me..
回答1:
In your servlet, do the following in the do[Get,Post]()
method
JSONObject jsonObject = JSONObject.fromObject( request.getQueryString() );
String username= jsonObject.get( "username" );
String password= jsonObject.get( "password" );
String type= jsonObject.get( "type" );
You also need the remove the following line from your JS.
request = JSON.parse(data);
来源:https://stackoverflow.com/questions/17002805/get-value-separately-from-json-object-in-java-servlet